c++ - 为什么我们应该为这段代码使用指针?

标签 c++ iterator

我从 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/

相关文章:

c++ - 二维 vector 的迭代器

python - iter,for循环python中的范围

c++ - 误报警告 PVS Studio : V808 object of type was created but was not utilized

c++ - 为什么有两个 std::allocator::construct 函数?

c++ 0x在模板中继承构造函数

c++ - .lib 中的主要功能作为启动功能?

c++ - 使用迭代器进行内存高效的词法分析

c++ - 为什么与 "end()"迭代器进行比较是合法的?

c++ - 通过 UDP 套接字手动发送到 iperf? (C++)

c++ - 将 vector 迭代器转换为成员指针