Elior
Elior

Reputation: 3266

for loop with different types c++

I have a for loop which i need to loop over different kinds of arrays, the first one is map<string,vector<string>> and the second is an integer array.

to implement this i did :

struct {map<string,vector<string>>::iterator it; int i; } s;
int k = 0;
for ( s.it = m.begin(), s.i = 0; s.it != m.end(), s.i < size; s.i+=2)
{
    while (k != integer_array[s.i] && k < size)
    {
            s.it++;
        k++;
    }       
    if (k == integer_array[s.i])
    {
        cout << s.it.first << endl; // this line does not complie       
        k = 0;
            s.it = m.begin();
    }
}

explain of what i'm trying to do: integer_array stores indexes and i'm trying to print the map value at index which stored in integer_array. any suggestions?

Upvotes: 0

Views: 122

Answers (1)

paercebal
paercebal

Reputation: 83309

I guess your problem is in the iterator.

Instead of:

    cout << s.it.first << endl;

Try:

    cout << s.it->first << endl;

The reason is that a STL iterator behaves like a pointer: if you want to access the value pointed, then you must dereference your iterator (either through operator * or through operator ->).

In the current case, the pointed value is a std::pair of std::string and std::vector, and you want to print the first std::string. Thus, you need to write it->first.

Upvotes: 1

Related Questions