map iterator

T

thomas

a question about map iterator

---code---
#include<map>
#include<iterator>
using namespace std;

int main(){
map<string,int> mp;
mp.insert(pair<string,int>("hello",1));
for(map<string,int>::iterator it(mp.begin()); it<mp.end(); it+
+) ///----L---
cout<<it->first<<endl;
}
----code ----

it cannot compile; if I change the "it<mp.end()" to "it!=mp.end()"
in line L , it works.

for int vectors, I can use "it<vi.end()" to make boundary check, but
for map it doesn't works.

any explaination or suggestions?
 
A

Andrew Koenig

for int vectors, I can use "it<vi.end()" to make boundary check, but
for map it doesn't works.
any explaination or suggestions?

Vector iterators are random-access iterators. Map iterators aren't. If
this doesn't answer your question completely, please study the definition of
random-access iterators carefully.
 
J

Jim Langston

thomas said:
a question about map iterator

---code---
#include<map>
#include<iterator>
using namespace std;

int main(){
map<string,int> mp;
mp.insert(pair<string,int>("hello",1));
for(map<string,int>::iterator it(mp.begin()); it<mp.end(); it+
+) ///----L---
cout<<it->first<<endl;
}
----code ----

it cannot compile; if I change the "it<mp.end()" to "it!=mp.end()"
in line L , it works.

for int vectors, I can use "it<vi.end()" to make boundary check, but
for map it doesn't works.

any explaination or suggestions?

You've already gotten the explanation. The suggestion is instead of using <
use !=

for(map<string,int>::iterator it(mp.begin()); it != mp.end(); ++it) {
cout<<it->first<<endl;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top