【问题标题】:why i'm getting error: no match for ‘operator<<?为什么我收到错误:'operator<<? 不匹配?
【发布时间】:2019-03-18 23:47:44
【问题描述】:

我现在是编程和学习 C++ 中向量的初学者。我想显示向量的第一个元素的地址 使用下标和指针。程序 1 工作正常,但在 程序 2-

中出现编译错误

error: no match for ‘operator+’ (operand types are ‘std::vector<int>’ and ‘int’) cout<<*(num+1)<<endl;
方案一:

#include<iostream>
#include<vector> 
using namespace std;

int main()
 {
   vector<int> num;
   //Enter the numbers

   for(int i=0;i<10;i++)
     num.push_back(i);


   //Display address of first element using subscript
   cout<<&num[1]<<endl;


   return 0;
 }


方案二: 除了代替下标之外,所有代码都是相同的,我想在指针的帮助下显示地址。

 //Display address of first element using pointer

   cout<<*(num+1)<<endl;

我也试过

cout<<(num.begin()+1)<<endl;

但它显示相同的错误。

【问题讨论】:

  • A std::vector 不是指针,也不提供operator+。因此num+1 没有意义
  • 这个错误是不言自明的。您正在尝试添加std::vector1。你可能想做num.data() + 1之类的事情。
  • //Display address of first element using subscript ... cout&lt;&lt;&amp;num[1]&lt;&lt;endl; 你的评论是在撒谎。 num[1] 不是第一个元素。
  • num[0] 是第零个元素@Swordfish
  • @user4156958 roflmao

标签: c++ c++11 pointers vector


【解决方案1】:

a[b] 仅在应用于指针时等效于*(a+b)。 (还有数组,因为在这种情况下它们会自动转换为指针。)

std::vector 不是指针。它是一个类(准确地说是一个类模板)。通常[] 对类不起作用,但std::vector 重载 运算符[],这意味着它提供了一个特殊的成员函数,该函数在使用[] 时执行。

std::vector 不会重载+,因此+ 不能应用于向量。

如果您要编写自己的 vector,您可以轻松地重载 + 以按照您的意愿行事。

【讨论】:

  • 我也尝试这样做cout&lt;&lt;(num.begin()+1)&lt;&lt;endl;,但它显示相同的错误。
  • @user4156958 因为num.begin() 返回一个迭代器,而不是一个指针。将1 添加到它之后,它仍然是一个迭代器。 std::cout 不知道如何打印迭代器。如果您想获得指向向量第一个元素的指针,请按照您问题下 cmets 中的建议使用 num.data()
  • @Swordfish 谢谢。然后num.data()+1 就是它的全部。我真的需要睡觉了。
  • 虽然正确,但为了完整起见,我要提一下 std::vector 不是类,而是为给定类型实例化的模板容器类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-03
  • 2013-04-22
  • 2017-01-04
  • 1970-01-01
  • 2022-06-29
  • 1970-01-01
  • 2021-12-07
相关资源
最近更新 更多