yapkm01
yapkm01

Reputation: 3775

C++ member function called begin() question

Assuming that:

vector<string> mvec; 

has some elements on it

Partial code:

for(vector<string>::iterator it1 = mvec.begin(); it1 != mvec.end(); ++it1) {  
for(string::iterator it2 = it1->begin(); it2 != it1->end(); ++it2)

since:

it1->begin() deference the object and then invoke the member function begin() of that object, which object is it1 pointing to?

String?

Upvotes: 3

Views: 126

Answers (5)

Constantinius
Constantinius

Reputation: 35059

it1 is pointing to an instance of the string class stored within the vector.

Upvotes: 5

user2100815
user2100815

Reputation:

This code:

#include <vector>
#include <string>
#include <iostream>
using namespace std;

int main() {
    vector <string> mvec;
    mvec.push_back("foo");
    mvec.push_back("bar");
    for(vector<string>::iterator it1 = mvec.begin(); it1 != mvec.end(); ++it1) {  
        for(string::iterator it2 = it1->begin(); it2 != it1->end(); ++it2) {
            cout << * it2 << endl;
        }
    }
}

Prints:

f
o
o
b
a
r

The first iterator gives you access to the strings in the vector, and the second to the characters in the strings.

Upvotes: 2

Seth Carnegie
Seth Carnegie

Reputation: 75130

Like others have said, dereferencing it1 will get you a string. It may seem weird, given that it1 isn't a pointer, but the iterator class overloads the operator->, in which case all bets are off in regards to what will happen.

Upvotes: 1

Naveen
Naveen

Reputation: 73443

Since it1 is an iterator for vector<string> when you derefence it you will get a string.

Upvotes: 5

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

Yes, it's the string, which is also a container, so de-referencing it2 would get you its individual characters.

Upvotes: 1

Related Questions