I am fairly new to c++, I dont really have any background in it. I am tying to create a list of tuples, the first will be an int, the second will be a string.
The answers here are a bit outdated, and don't tell you how to sort the list.
Since C++11 you can use the standard tuple, with a vector
for example:
#include
#include
// ...
vector> data;
To add entries you can use the emplace_back method of vector
.
Here's an example reading from the standard input:
#include
// ...
int age;
string name;
while(cin >> age >> name) data.emplace_back(age, name);
To sort, it is sufficient to use the standard sort function, since int
is the first element of the tuple in our case, the default sorting order will sort the elements by int
s first, then by string
s:
#include
// ...
sort(data.begin(), data.end());
You can retrieve values from a tuple by index:
get<0>(data[i])
or by type:
get(data[i])
I've put together a full example that you can see live at ideone.