Adam Jakiela
Adam Jakiela

Reputation: 2248

Referencing a Value from a Nested Pair in a Map

I have a map which contains an int and a nested pair of two strings:

map<int, pair<string, string> > books;

I also have a vector of strings.

vector<string> returned;  

And the two iterators which accompany them:

vector<string> returned::iterator it2; 
map<int, pair<string, string> >::iterator it3; 

I am trying to access the first string of the pair which is nested in the map to compare it to the current string of the vector "returned". I am using two iterators to do this. However, I cannot seem to access the first string of the nested pair.

//PUT BACK BORROWED BOOKS    
for (it2 = returned.begin(); it2 != returned.end(); it2++){ 
    //SEARCH FOR POSITION OF BOOK 
    for (it3 = books.begin(); it3 != books.end(); it3++){   
                    //PROBLEM IN LINE BELOW
        if(it2 == (it3->second-> first)) 
            int bookPos = it3 -> first;  


    }
}

Does anyone know how to reference this first string in the pair? Obviously "it->second-> first" is not the solution.

Thanks in advance.

Upvotes: 5

Views: 1669

Answers (2)

Elizabeth Bradley
Elizabeth Bradley

Reputation: 741

Maps also make good lookup tables. The map key corresponds to two values represented by a pair. The example below shows how to access the key and pair values.

int main()
{
typedef map<string, pair<int, int> > op_type;
op_type op = {
             {"addu", make_pair(33, 1) }
             };

vector<string> this_line;

op_type::const_iterator i = op.find(this_line[0]);
if( i != op.end() )
{
    cout << "key: " << i-first << endl;
    cout << ".first value in pair " << i->second.first << endl;
    cout << ".second value in pair " << i->second.second << endl;
}
}

Prints: key: addu .first value in pair 33 .second value in pair 1

Upvotes: 0

Leonid Volnitsky
Leonid Volnitsky

Reputation: 9144

There are two errors. it3->second is not an iterator. Also as was mentioned in comments, you are comparing it2 (iterator) with a string. Line with error should look like this:

if(*it2 == (it3->second.first))

Upvotes: 3

Related Questions