map iterator

Discussion in 'C++' started by thomas, Jul 6, 2008.

  1. thomas

    thomas Guest

    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?
    thomas, Jul 6, 2008
    #1
    1. Advertising

  2. "thomas" <> wrote in message
    news:...

    > 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.
    Andrew Koenig, Jul 6, 2008
    #2
    1. Advertising

  3. thomas

    Jim Langston Guest

    "thomas" <> wrote in message
    news:...
    >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;
    }
    Jim Langston, Jul 8, 2008
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hendrik Maryns
    Replies:
    18
    Views:
    1,398
  2. greg
    Replies:
    6
    Views:
    444
    Dietmar Kuehl
    Jul 17, 2003
  3. wolverine
    Replies:
    3
    Views:
    1,054
    Chris
    Jul 31, 2006
  4. Vikram Karandikar
    Replies:
    1
    Views:
    183
    Vikram Karandikar
    Oct 25, 2013
  5. Jim Anderson

    problem with iterator (map iterator)

    Jim Anderson, Jan 10, 2014, in forum: C++
    Replies:
    3
    Views:
    108
    Luca Risolia
    Jan 13, 2014
Loading...

Share This Page