【发布时间】: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::vector和1。你可能想做num.data() + 1之类的事情。 -
//Display address of first element using subscript ... cout<<&num[1]<<endl;你的评论是在撒谎。num[1]不是第一个元素。 -
num[0] 是第零个元素@Swordfish
-
@user4156958 roflmao