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!