Gman Gman - 9 days ago 14x
C++ Question

How do I insert two values into a <list> or <vector> so that I can retrieve values later on?

I would like to be able to use insert(int, int) and then be able to retrieve all values of second int based on what the first int is. If I did


auto p=;
for(int i=0; i<string.size(3); ++i)
std::cout << p[i] << " ";

This would print out 5 3 9. I'm just having trouble grasping how it would store the values in such a fashion to be able to retrieve them in order like that.

class key_value_sequences{
int size(int key) const;
const int* data(int key) const;
void insert(int key, int value);
int key;
int value;
int size;

void insert(key, value){
std:list<std::pair<key, value>> myList;

const int* data(key) const{


int size(key) const{
int size=myList.size(key);
return size;


It sounds to me like you need a multimap. A map is a container that allows you to insert key / value pairs, where keys can be used to look up values. A multimap allows you to have multiple values associated with a single key.

For example:

    std::multimap<int, int> myMap;

    myMap.insert( std::make_pair( 0, 8 ) );
    myMap.insert( std::make_pair( 0, 5 ) );
    myMap.insert( std::make_pair( 0, 7 ) );
    myMap.insert( std::make_pair( 1, 15 ) );

    // equal_range() returns a pair of iterators pointing to the first item
    // in the list for the specified key, and one past the final item containing
    // the key.
    auto searchResultIteratorPair = myMap.equal_range( 0 );

    // Print out the values found
    for( auto it = searchResultIteratorPair.first; it != searchResultIteratorPair.second; it++ )
        std::cout << "Value: " << it->second << std::endl;

If my assumption was wrong and you really did want to use a list / vector, then you would need to create them as a list / vector of pairs. Then to find items you would iterate the entire list and check each pair to see if it matched your criteria.

For example:

std::list< std::pair<int, int> > myList;

    myList.push_back( std::make_pair( 0, 8 ) );
    myList.push_back( std::make_pair( 0, 5 ) );
    myList.push_back( std::make_pair( 0, 7 ) );
    myList.push_back( std::make_pair( 1, 15 ) );

    int searchValue = 0;
    for( auto it = myList.begin(); it != myList.end(); it++ )
        if( it->first != searchValue )

        std::cout << "Value: " << it->second << std::endl;