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 开发者_Go百科the object and then invoke the member function begin() of that object, which object is it1 pointing to?
String?
Since it1
is an iterator
for vector<string>
when you derefence it you will get a string
.
it1
is pointing to an instance of the string class stored within the vector.
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.
Yes, it's the string
, which is also a container, so de-referencing it2
would get you its individual characters.
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.
精彩评论