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?
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 ie:
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 ie:
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:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.