• FEATURED

View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# Sorting Vector containers in C++

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

17 replies to this topic

### #1rherm23  Members

Posted 09 July 2012 - 05:44 PM

I have a struct like so ..

[source lang="cpp"]struct STUFF{int points;string first_name;string last_name;}[/source]

I have a vector <STUFF> stuffs and i wanted to sort the data inside from highest to lowest using the pts value. Is something like that possible?
I havent used c++ in a while and i started fleshing out this program and was stumped on this problem. Im going to be displaying the players according to the pts value in each struct so the person with the most points should be at index [0] and the last place person at the last index.

Im gonna keep at it but i think that any ideas i might be having might be too complicated and a more elegant solution may exist.

Thanks in advance for any help and replies.
"choices always were a problem for you......" Maynard James Keenan

### #2DevLiquidKnight  Members

Posted 09 July 2012 - 06:02 PM

POPULAR

Something like:

[source lang="cpp"]struct MyStruct{ int key; std::string stringValue; MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}};struct less_than_key{ inline bool operator() (const MyStruct& struct1, const MyStruct& struct2) { return (struct1.key < struct2.key); }};std::vector < MyStruct > vec;vec.push_back(MyStruct(4, "test"));vec.push_back(MyStruct(3, "a"));vec.push_back(MyStruct(2, "is"));vec.push_back(MyStruct(1, "this"));sort(vec.begin(), vec.end(), less_than_key());[/source]

Edited by DevLiquidKnight, 09 July 2012 - 06:04 PM.

### #3Bregma  Members

Posted 09 July 2012 - 07:29 PM

POPULAR

Here's a complete, tested program that demonstrates the easiest way to do what you ask using the current standard C++ language.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct STUFF
{
int points;
string first_name;
string last_name;
};

int main()
{
// Create and initialize a vector of STUFF.
vector<STUFF> stuffs = {
{ 7, "one",   "seven" },
{ 8, "two",   "eight" },
{ 5, "three", "five"  },
{ 1, "four",  "one"   },
{ 3, "five",  "three" },
};

// Sort the vector on points.
sort(stuffs.begin(), stuffs.end(),
[](const STUFF& lhs, const STUFF& rhs) -> bool
{ return lhs.points < rhs.points; });

// Print the stuffs.
for (const auto& stuff: stuffs)
{
cout << stuff.points << " " << stuff.first_name << " " << stuff.last_name << "\n";
}
}


Stephen M. Webb
Professional Free Software Developer

### #4rherm23  Members

Posted 09 July 2012 - 08:20 PM

Thanks for the replies. Ill tst them when i get home from work. I appreciate it. +reps to you both.
"choices always were a problem for you......" Maynard James Keenan

### #5BeerNutts  Members

Posted 09 July 2012 - 09:32 PM


sort(stuffs.begin(), stuffs.end(),
[](const STUFF& lhs, const STUFF& rhs) -> bool
{ return lhs.points < rhs.points; });



I have never seen anything like that in C++. Could you provide a link that explains it?

BTW, IMO, in a For Beginner's forum, you should explain what you've done, or give a simpler solution, as DevLiquidKnight did.
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

### #6rnlf  Members

Posted 09 July 2012 - 11:06 PM


sort(stuffs.begin(), stuffs.end(),
[](const STUFF& lhs, const STUFF& rhs) -> bool
{ return lhs.points < rhs.points; });



I have never seen anything like that in C++. Could you provide a link that explains it?

BTW, IMO, in a For Beginner's forum, you should explain what you've done, or give a simpler solution, as DevLiquidKnight did.

I guess, what you have never seen is the lambda function used as the comparison operator. What it basically does, is to create an anonymous (unnamed) function, that can be passed directly to function templates such as sort. http://en.wikipedia.org/wiki/Anonymous_function#C.2B.2B should explain this well.

Edited by rnlf, 09 July 2012 - 11:07 PM.

### #7Servant of the Lord  Members

Posted 09 July 2012 - 11:45 PM

POPULAR


sort(stuffs.begin(), stuffs.end(),
[](const STUFF& lhs, const STUFF& rhs) -> bool
{ return lhs.points < rhs.points; });



I have never seen anything like that in C++. Could you provide a link that explains it?

Bregma's method is from the new C++11 standard (he mentioned this: "

demonstrates the easiest way to do what you ask using the current standard C++ language").

His for() function to print vector probably looks funky as well, since it's also from the new C++11 standard.

// Print the stuffs.
for (const auto& stuff: stuffs)
{
cout << stuff.points << " " << stuff.first_name << " " << stuff.last_name << "\n";
}


Infact, his vector initialization probably looks a bit wonky also:
vector<STUFF> stuffs = {
{ 7, "one",   "seven" },
{ 8, "two",   "eight" },
{ 5, "three", "five"  },
{ 1, "four",  "one"   },
{ 3, "five",  "three" },
};

Here's his code explained:

Create and initialize a std::vector of STUFF structs, using C++11's uniform initialization.

  vector<STUFF> stuffs = {
{ 7, "one",   "seven" },
{ 8, "two",   "eight" },
{ 5, "three", "five"  },
{ 1, "four",  "one"   },
{ 3, "five",  "three" },
};

The vector is taking a bunch of instances of STUFF, separated by commas, between curly brackets.
vector<STUFF> stuffs = { , , , , };

However, each instance is also being constructed and initialized using uniform initialization.
Each member variable of the STUFF struct is being initialized by an built-in initialization constructor
struct STUFF
{
int points;
string first_name;
string last_name;
};

STUFF myStuff = { 7 /* points */, "one" /* first_name */,   "seven" /* last_name */};

The std::sort() algorithm function takes three parameters*. The first parameter is an iterator saying where in the container to begin sorting, the second parameter says at what point to stop sorting, and the third parameter is a callback function (or functor object) that is used to describe how to sort the elements of the container.

sort(stuffs.begin(), stuffs.end(), /* callback function goes here */);

*The last parameter is actually optional, by function overloading, and defaults to the member function operator<.

Bregma was using a Lambda function. That is, he was creating an anonymous function inline right there as the third parameter, and using that as the callback function.
sort(stuffs.begin(), stuffs.end(),
[](const STUFF& lhs, const STUFF& rhs) -> bool
{ return lhs.points < rhs.points; });

Lambdas syntax works like this:
[ /*local parameters to capture */]( /* normal function parameters */) -> /* return value type */ { /* function body */ }
The return value type of the lambda is using Alternative Function Syntax.

The for() loop printing out the results contains two C++11 features.

for (const auto& stuff: stuffs)
{
cout << stuff.points << " " << stuff.first_name << " " << stuff.last_name << "\n";
}

First, normal for() loops take three parameters, separated by semi-colons.
//A normal for() loop:
for( /* initialization of variables separated by commas */ ; /* Comparison, to end the loop if evaluated to true */ ; /* Called every loop usually to increment the variables */

//Example:
std::vector<std::string> myStrings;
for(int i = 0; i < myStrings.size(); i++)
{
std::string str = myStrings[i];
std::cout << str << std::endl;
}

A new for() loop style was added by C++, called range-for(). It allows you to sort-hand common iteration over containers and arrays.
It takes two parameters seperated by a colon (not a semi-colon). The first parameter is a temporary variable that will hold/reference each element, and the second parameter is a container of elements.
std::vector<std::string> myStrings;
for(std::string str : myStrings)
{
std::cout << str << std::endl;
}

It gets rid of alot of boilerplate code in alot of common situations. There are reasons to use both styles of for() loops, so it doesn't replace the old one, just serves as an additional version in your toolset.

(For the record, it'd be more proper for the variable in the example I gave above to be a reference or const reference, but it doesn't have to be)

for(const std::string &str : myStrings)

The second new feature used in the for-loop was the 'auto' type of variable used for type inference.
The type of 'auto' is automatically deduced at compile-time, so it's still as strongly-typed as ever, but is much more convenient in some situations like very long variable names...
//Constructing and initializing a vector iterator the old way:
std::vector< std::pair<bool, std::string> >::iterator myIterator = myVector.begin(); //Woah! That's a mouthful of code, and it serves no purpose either... We just want an iterator.
auto myIterator = myVector.begin(); //Easy! And just as type-safe.

...or funny-syntaxed variable names...
void *myFuncPtr(int, float, std::string) = &MyFunction;
auto *myFuncPtr = &MyFunction;

...or when the type you are wanting, you don't actually know what it'll be (such as in templates).

And for the original poster:
#include <algorithm> //Needed for std::sort() algorithm.
#include <iostream> //Needed for std::cout for displaying the results.
#include <string> //Needed for std::string.
#include <vector> //Needed for std::vector.

These are all standard parts of modern C++ (The previously named C++0x standard was passed last year successfully, becoming C++11, replacing the C++98 and C++03 standards). Most of them are implemented in the major compilers already, though you may need to tell the compilers to enable them.

The new standard makes C++ faster, safer, more flexible, and funner to work with.

BTW, IMO, in a For Beginner's forum, you should explain what you've done, or give a simpler solution, as DevLiquidKnight did.

Neither chunks of code were commented, and both are simple to advanced C++ users but confusing to newer users - it just happens that the method Bregma used is unfamiliar because it's rather new (and to be fair, he said it was from the new standard, though maybe not as clearly as he intended to). DevLiquidKnight's version would be equally confusing to newer programmers (or at least equally confusing to me when I was a new programmer).

I suggest reading through the new C++11 features - there are alot more. I also strongly recommend the videos of the Going Native 2012 C++ conference - very very informative and interesting.

I'm using a few of them on a regular basis in my code now, and have for several months. I haven't yet taken full advantage of all the new features (I've only used lambdas once or twice so far, mostly from inexperience), and haven't yet learned all the new C++11 standard library additions (like better random number generators, and better smart pointers, and regex capabillities, and more), but I tend to work more and more of C++11 into my coding toolbox gradually. Very cool additions.

My favorite C++11 addition (which I only just got access last night when I updated to the most recent MinGW compiler), is in-class member initialization.
class Point
{
public:
int x = 0; //Initialized to zero at construction! Woot!
int y = 0;
};

You can also chain constructors now.
class Point
{
public:
Point() : Point(0,0) { } //Constructor chaining. This constructor calls the other constructor.
Point(int x, int y) : x(x), y(y) { }

private:
int x, y;
}

I also make heavy use of the new strongly-typed enums.
enum class Color {Red, Green, Blue}; //Note the 'class' keyword after the enum. This makes it strongly-typed.

Color color = Color::Red; //It's in it's own namespace, and doesn't automatically get converted to integers!

Enjoy!

Edited by Servant of the Lord, 09 July 2012 - 11:47 PM.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #8larspensjo  Members

Posted 10 July 2012 - 04:55 AM

I have a struct like so ..

[source lang="cpp"]struct STUFF{int points;string first_name;string last_name;}[/source]

I have a vector <STUFF> stuffs and i wanted to sort the data inside from highest to lowest using the pts value. Is something like that possible?
I havent used c++ in a while and i started fleshing out this program and was stumped on this problem. Im going to be displaying the players according to the pts value in each struct so the person with the most points should be at index [0] and the last place person at the last index.

Im gonna keep at it but i think that any ideas i might be having might be too complicated and a more elegant solution may exist.

Thanks in advance for any help and replies.

It looks like an easy solution is to change std::vector into std::set. It is another container type that will sort the entries automatically. That means some changes, which may or may not be fine with you:
• You can't access elements using []-operator. Instead you need to iterate "for (auto it = stuffs.begin(); it != stuffs.end(); it++)", but that will produce the elements in the order you want.
• You need to define a comparison operator for STUFF.

Edited by larspensjo, 10 July 2012 - 04:58 AM.

Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

### #9ASnogarD  Members

Posted 10 July 2012 - 05:48 AM

This lot, the discussion about C++11 compliance and VS compliance has gave me quiet a startle... now I wonder what I can use or cant, if an piece of code fails due to none compliance or bad coding on my part.

Made me also wonder if VS is the compiler for me, I only use it because I am using the express ( free ) version and I figured it would be pretty much up to date compliance wise. Makes me wonder if I shouldnt look to using some other compiler, especially if I can lose the hassle of convincing users of my code to get the runtime dll for VS10.

... but I suppose at my current level ( beginner - intermediate sort of ) it wont really effect me , right ?

### #10rnlf  Members

Posted 10 July 2012 - 07:03 AM

It will. If you try to learn modern C++, you should not have to learn all the old techniques which were required back in the day, but have been replaced with safer, easier and faster solutions in C++11. You get the GNU compiler collection for free, too, you get IDEs for every popular operating system for free. Why not profit from their quicker adoption of C++11?

### #11way2lazy2care  Members

Posted 10 July 2012 - 07:53 AM

If you define some operators for it (< specifically), you should be able to use std::sort without having to do any lambda functions. Though it may be more fun/informative to do it that way (if you do it correctly).

edit: Ah. it looks like SoL mentioned this, but it was deep in his uber-post.

Edited by way2lazy2care, 10 July 2012 - 08:00 AM.

### #12BeerNutts  Members

Posted 10 July 2012 - 08:13 AM

Well, I think this thread got side-tracked, and the OP is thoroughly confused, but I appreciate the explanation. I have not even looked at anything form C++11, so I'll be going over this stuff now.

Thanks SOL.
My Gamedev Journal: 2D Game Making, the Easy Way

---(Old Blog, still has good info): 2dGameMaking
-----
"No one ever posts on that message board; it's too crowded." - Yoga Berra (sorta)

### #13Servant of the Lord  Members

Posted 10 July 2012 - 11:14 AM

No problem... and I did side-track the thread, oops.

This lot, the discussion about C++11 compliance and VS compliance has gave me quiet a startle... now I wonder what I can use or cant, if an piece of code fails due to none compliance or bad coding on my part.

Made me also wonder if VS is the compiler for me, I only use it because I am using the express ( free ) version and I figured it would be pretty much up to date compliance wise. Makes me wonder if I shouldnt look to using some other compiler, especially if I can lose the hassle of convincing users of my code to get the runtime dll for VS10.

... but I suppose at my current level ( beginner - intermediate sort of ) it wont really effect me , right ?

The new C++11 features make C++ easier to use as a beginner, so it's definitely something you should look into and learn piece by piece overtime, in the same way you learn the current version of C++ piece by piece over time.

Any old code won't become non-compliant - it's an extension of the previous standards, without discarding any previous parts.
Because the standard is so new (2011, hence the name), no compiler currently implements every part of the standard, though because working drafts of the standard have been available for years, the major compilers (Microsoft's and GCC/MinGW) already implement the majority of it, and certainly all the parts I mentioned in my post.

Some compilers require you to pass in a certain command-line parameter to 'unlock' the new features. GCC/MinGW requires '-std=c++11' to be passed in. (Presumably when they are 100% sure they've implemented the standard, it'd be turned on by default).
So your compiler may actually already be compliant, but you just accidentally have it turned off or it might be turned off by default. But it's perfectly stable and guaranteed not to change because it's been officially and permanently standardized.

Or, you just might be using an older version of your compiler, and just need to update to the most recent version.
There's no need to update this second, and no harm comes from waiting another year or so... I just wanted to get a a jump on C++11 myself, because the additions are so great, and because I'll need to learn them sooner or later anyway.

Uh, so to simplify:
- Definitely for beginners AND pros
- Old code still works fine, even if you update
- New features are awesome
- Visual Studio and GCC/MinGW have all the new features I mentioned, and more
- You'll want to learn them eventually, but it doesn't have to be now
- But you can use them now if you desire, just update your compiler

Edited by Servant of the Lord, 10 July 2012 - 11:16 AM.

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #14rnlf  Members

Posted 10 July 2012 - 11:39 PM

Some compilers require you to pass in a certain command-line parameter to 'unlock' the new features. GCC/MinGW requires '-std=c++11' to be passed in.

Just a minor correction here: In GCC versions prior to 4.7 (which is not yet available out of the box for a lot of linux distros), the flag is '-std=c++0x'.

### #15Servant of the Lord  Members

Posted 11 July 2012 - 12:04 AM

It's perfectly fine to abbreviate my username to 'Servant' or 'SotL' rather than copy+pasting it all the time.
All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.
Of Stranger Flames -

### #16larspensjo  Members

Posted 11 July 2012 - 04:23 AM

Another detail that may be important, is that GCC 4.7 is not compatible with earlier versions on binary level. I got hit by this when I did "mingw-get upgrade", and my development environment stopped working.
Current project: Ephenation.
Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/

### #17Bregma  Members

Posted 11 July 2012 - 05:22 AM

Another detail that may be important, is that GCC 4.7 is not compatible with earlier versions on binary level. I got hit by this when I did "mingw-get upgrade", and my development environment stopped working.

Yes, there was a nasty ABI fart. You would notice it if you expose a std::list in your API and you try to link two modules using that API built with two different versions. The problem was only noticed when Linux distros started using that compiler version in a big way with C++ features enabled (Firefox and Ubuntu's Unity desktop use C++11). The Ogre game framework is affected but does not require C++11 in released versions.

The bug was fixed in 4.7.2 and later (by reverting the C++11-required O(1) size() feature in std::list).

There was also a similar problem in C++ std::string.

Avoid using GCC 4.7.0 or 4.71.
Stephen M. Webb
Professional Free Software Developer

### #18Matt-D  Members

Posted 11 July 2012 - 11:17 AM

I have a struct like so ..
[source lang="cpp"]struct STUFF{int points;string first_name;string last_name;}[/source]
I have a vector <STUFF> stuffs and i wanted to sort the data inside from highest to lowest using the pts value. Is something like that possible?
I havent used c++ in a while and i started fleshing out this program and was stumped on this problem. Im going to be displaying the players according to the pts value in each struct so the person with the most points should be at index [0] and the last place person at the last index.

Im gonna keep at it but i think that any ideas i might be having might be too complicated and a more elegant solution may exist.

Thanks in advance for any help and replies.

Here's the solution: http://vegardno.blog...jects-in-c.html

Note, that using "std::string::operator<" is not optimal -- however, "std::string" happens to implement a member function "compare", which is better.

The blog post shows a simple perf comparison of the two above-mentioned approaches:
"Running this on my laptop, it takes approximately 3.9 seconds to run the original code and 2.9 seconds to run the new version."

EDIT: Ah, noticed you only need to sort by "points", that's a simpler case; then, I'll only keep this reply in case anyone wanders in here by Google search and tries to do sorting via strings... ;-)

Edited by Matt-D, 11 July 2012 - 11:20 AM.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.