Sorting Vector containers in C++

Started by
16 comments, last by Matt-D 11 years, 9 months ago
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
Advertisement
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]
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

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



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)


[quote name='Bregma' timestamp='1341883765' post='4957470']


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.
[/quote]

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.

[quote name='Bregma' timestamp='1341883765' post='4957470']


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?[/quote]

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

[background=rgb(250, 251, 252)]demonstrates the easiest way to do what you ask using the current standard C++ language").[/background]




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:

[hr]

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 */};


[hr]

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 */);

*[size=2]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.

[hr]

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;
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)

[hr]

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).

[hr]

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.


[hr]

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. tongue.png


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

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). smile.png

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! smile.png

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 add new elements with "stuffs.insert()" instead of "stuffs.push_back()".
  • You need to define a comparison operator for STUFF.
[size=2]Current project: Ephenation.
[size=2]Sharing OpenGL experiences: http://ephenationopengl.blogspot.com/
blink.png 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 ?
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?

This topic is closed to new replies.

Advertisement