how to properly iterate over a container

closed account (Dy7SLyTq)
so i have a container called Source that is of type std::map<std::string, std::vector<std::string>> but when I try to print it with this function:

1
2
3
4
5
6
void Lexer::PrintSource()
{
    for(auto Iterator = this->Source.begin(); Iterator != this->Source.end(); Iterator++)
        for(auto SubIterator = Iterator->begin(); SubIterator != Iterator->end(); SubIterator++)
            cout<< *SubIterator << endl;
}


i get these errors:

Lexer.cpp: In member function 'void Lexer::PrintSource()':
Lexer.cpp:29:42: error: 'struct std::pair<const std::basic_string<char>, std::vector<std::basic_string<char> > >' has no member named 'begin'
         for(auto SubIterator = Iterator->begin(); SubIterator != Iterator->end(); SubIterator++)
                                          ^
Lexer.cpp:29:76: error: 'struct std::pair<const std::basic_string<char>, std::vector<std::basic_string<char> > >' has no member named 'end'
         for(auto SubIterator = Iterator->begin(); SubIterator != Iterator->end(); SubIterator++)
                                                                            ^
'Iterator' is a iterator to a map. Which means *Iterator is a pair<string,vector<blah>>.

If you want to iterate over the vector:

1
2
3
    for(auto Iterator = this->Source.begin(); Iterator != this->Source.end(); ++Iterator) // favor prefix form of ++
        for(auto SubIterator = Iterator->second.begin(); SubIterator != Iterator->second.end(); ++SubIterator)
            cout<< *SubIterator << endl;


Or... more simply:

1
2
3
for(auto& i : Source)
    for(auto& sub : i.second)
        cout << sub << endl;
closed account (Dy7SLyTq)
thank you that worked
closed account (Dy7SLyTq)
one more question:
is it possible to convert an iterator to int to find out how many times it has iterated through the container?
For most containers... no. Having that ability would mean the container would have to be indexed.

For random access containers (like vector), however... yes:

 
int index = myiter - myvector.begin();
> is it possible to convert an iterator to int to find out how many times it has iterated through the container?

Obviously yes. It is the number of times std::begin(cntr) would have to be incremented before it becomes equal to the iterator.

auto pos = std::distance( some_iter, std::begin(cntr) ) ;
http://en.cppreference.com/w/cpp/iterator/distance

O(1) if the iterator is a RandomAccessIterator, linear otherwise.
Whooop forgot about std::distance.

Though just note, as you mentioned it's linear complexity for non-random access containers so it's less "conversion" and more "iterating over the container again".
Topic archived. No new replies allowed.