我从 C++ 教程中找到了以下代码。 在:
cout << "value of v = " << *v << endl;
可以看到使用了*v
。你能告诉我为什么我们不应该使用 v
而不是 *v
吗?
#include "StdAfx.h"
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// create a vector to store int
vector<int> vec;
int i;
// access 5 values from the vector
for(i = 0; i < 5; i++){
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
cin.get();
cin.get();
return 0;
}
最佳答案
v
的类型是
vector<int>::iterator v
因此,如果你尝试这样做
<< v << endl;
您会尝试将 iterator
写入输出流,而您想要的是 int
。因此,要取消引用迭代器,您可以使用 *
运算符获取迭代器中包含的基础对象
<< *v << endl
关于c++ - 为什么我们应该为这段代码使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38328462/