How to create a list of tuples C++

后端 未结 4 790
南方客
南方客 2021-02-14 08:06

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.

          


        
4条回答
  •  北海茫月
    2021-02-14 08:59

    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 ints first, then by strings:

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

提交回复
热议问题