Reputation: 1460
I have to read only the first two elements from an std::map
.
Here's my code:
#include<iostream>
#include<map>
#include<iterator>
using namespace std;
int main() {
map<int,int> a;
map<int,int>:: iterator itr;
itr = a.begin();
cout<<itr->first<<" "<<itr->second<<endl;
next(itr);
cout<<itr->first<<" "<<itr->second<<endl;
return 0;
}
I'm getting this error:
next
was not declared in the scope
what am I missing here and if there is a better way to do it?
Upvotes: 0
Views: 311
Reputation: 590
you should use itr++
to move itr forward to point next set of pairs. and you can access them by map->first;
and map->second;
Upvotes: 0
Reputation: 14637
For using std::next, you need to have at least C++11 compliant compiler.
std::next
returns a new incremented iterator. So, you need to use its return value to get the incremented iterator i.e.:
itr = next( itr );
Right now, itr
is pointing to the same element because the return value is not used.
If you meant to increment the itr
without a new iterator then std::advance is a better candidate here i.e.:
std::advance( itr, 1 );
If you're using a pre-C++11 compiler then you can use increment operator like this:
itr++;
Or,
++itr;
Here's a live demo.
In addition, the map is uninitialized/empty and you're trying to access its elements that are not there and this would result in Undefined Behavior.
Relevant read:
Upvotes: 2