user3243499
user3243499

Reputation: 3151

Correct way to iterate over a list of pairs in c++?

I have created a list of pairs of unordered_maps as follows:

list<pair<int, unordered_map<int, bool>>> calc;

And I am trying to iterate the list from right to left as follows:

for (list<int>::reverse_iterator rit = calc.rbegin(); rit != calc.rend(); ++rit) 
{
    int d = n - (*rit).first;

}

But The above is erroring out with message "request for member ‘first’ in ‘rit.std::reverse_iterator<_Iterator>::operator*<std::_List_iterator<int> >()’, which is of non-class type ‘int’"

Am I missing some syntax here?

Upvotes: 1

Views: 151

Answers (2)

R Sahu
R Sahu

Reputation: 206577

list<int>::reverse_iterator rit = calc.rbegin();

is not correct. It needs to be

list<pair<int, unordered_map<int, bool>>>::reverse_iterator rit = calc.rbegin();

You can make your life simpler and use:

auto rit = calc.rbegin();

Upvotes: 3

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136237

Correct syntax is:

using List = list<pair<int, unordered_map<int, bool>>>;
List calc;
for (List::reverse_iterator rit = calc.rbegin(); rit != calc.rend(); ++rit) 
{
    int d = n - (*rit).first;
}

You can use auto instead of List::reverse_iterator.

Upvotes: 3

Related Questions