【发布时间】:2016-11-14 16:06:04
【问题描述】:
我从 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是一个iterator,你需要取消引用它才能得到它的值 -
我不喜欢那个样本。更好的是
for(vector<int>::iterator v = vec.begin(); v != vec.end(); ++v)带有预增量或基于 C++11 范围的循环 -
样本很好,Dieter。