[英]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? it1-> begin()deference对象,然后调用该对象的成员函数begin(),哪个对象是it1指向?
String? 串?
it1
指向存储在向量中的字符串类的实例。
由于it1
是vector<string>
的iterator
,当你解除它时,你会得到一个string
。
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. 第一个迭代器使您可以访问向量中的字符串,第二个使用字符串中的字符。
是的,它是string
,它也是一个容器,所以取消引用it2
会得到它的个别字符。
Like others have said, dereferencing it1
will get you a string
. 像其他人所说的那样,取消引用
it1
会给你一个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. 它可能看起来很奇怪,因为
it1
不是一个指针,但iterator
类重载了operator->
,在这种情况下,所有的赌注都将关闭将要发生的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.