【问题标题】:why should we use pointer for this code?我们为什么要在这段代码中使用指针?
【发布时间】: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&lt;int&gt;::iterator v = vec.begin(); v != vec.end(); ++v) 带有预增量或基于 C++11 范围的循环
  • 样本很好,Dieter。

标签: c++ iterator


【解决方案1】:

vector&lt;int&gt;::iterator本质上是一个指向int 的指针。

更正式地说,迭代器类型重载了 dereference 运算符以返回迭代器当前引用的元素。

这就是为什么你需要写&lt;&lt; *v 如果你想抽象值。 (但如果 v 位于 vec.end() 则不要这样做 - 取消引用的行为未定义)。

【讨论】:

  • s/abstract/extract/?
【解决方案2】:

v的类型是

vector<int>::iterator v

因此,如果您尝试这样做

<< v << endl;

您会尝试将iterator 写入输出流,而您需要int。因此,要取消引用迭代器,您可以使用 * 运算符来获取包含在迭代器中的底层对象

<< *v << endl

【讨论】:

  • 谢谢,你能多解释一下vector::iterator v吗?
  • 看看阅读this post是否有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 2014-07-28
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 2016-04-09
相关资源
最近更新 更多