错误:在 c++ 中,"运算符+"操作数类型不匹配为"std::vector"<int>和"int"



错误:'operator+'操作数类型没有匹配项为'std::vector<int>'和c++中的"int">

为什么显示错误?

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout << "enter the total no. of elements you want in the array : n";
cin >> n;
vector<int> arr(n);
int inpt;
for (int i = 0; i < n; i++) {
cout << "enter the element you want in the array : n";
cin >> inpt;
arr.push_back(inpt);
}
vector<int> v;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (abs(arr[j] - i) == abs(arr[j + 1] - (i + 1))) {
v.push_back(arr[j]);
v.push_back(arr[j + 1]);
}
}
}
int s = v.size();
int s1 = s;
if (s == n) {
while (v[s] < v[s - 1]) {
s--;
}
int h = v[s - 1];
while (v[s1] < v[h]) {
s1--;
}
int c = v[s1];
std::swap(v[h], v[c]);
std::reverse(&v[h + 1], v + n);
for (auto m = v.begin(); m != v.end(); ++m) {
std::cout << *m << ' ';
}
}
else {
cout << "-1";
}
return 0;
}

我该如何纠正,我做错了什么?

std::reverse算法需要两个迭代器,第一个和最后一个。两者必须在同一容器的范围内
在您的情况下:std::reverse(&v[h+1],v+n);他们都指向错误的数据。首先:&v[h+1]是容器中值的地址,而不是迭代器。第二个是无效的,因为std::vector+int不起作用,因为在std::vector中没有运算符+重载。您想要的是第一个v.begin()+h+1,第二个v.begin()+n来获得迭代器。vector::iterator具有operator+operator++重载,因此它可以接受索引值。

提示!请记住,C++具有基于零的索引,因此大小为10的向量只能通过0到9之间的索引访问!确保您在代码中更正了这一点。

相关内容

最新更新