C++ 错误:与';不匹配;操作员+';操作数类型为';标准::向量<;int>';和';int';在c++;
错误:“运算符+”的操作数类型与c中的“std::vector”和“int”不匹配++ 为什么这是一个错误C++ 错误:与';不匹配;操作员+';操作数类型为';标准::向量<;int>';和';int';在c++;,c++,arrays,vector,C++,Arrays,Vector,错误:“运算符+”的操作数类型与c中的“std::vector”和“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";
#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;
int main()
{
int n;
cout>n;
向量arr(n);
int输入;
对于(int i=0;iinpt;
arr.push_back(输入);
}
向量v;
对于(int i=1;istd::reverse算法需要两个迭代器,第一个和最后一个。两者必须在同一容器的范围内。
在您的情况下:std::reverse(&v[h+1],v+n);
它们都指向错误的数据。第一:&v[h+1]
是容器中的地址到值,而不是迭代器。第二个无效,因为std::vector+int
无法工作,因为std::vector
中没有运算符+重载。
第一个是v.begin()+h+1
,第二个是v.begin()+n
,以获得迭代器。vector::迭代器
具有运算符+
和运算符+
重载,因此它可以接受索引值
< C++ >提示!记住C++具有基于零的索引,所以只能通过0到9的索引访问向量大小10!请确保在代码中纠正该错误。您期望代码< V+N>代码>做什么?<代码> STD::反向(& V[H+1),V+N);
:v
是向量而不是指针,所以你不能用它做指针运算。你的意思是&v[n]
?arr[j+1]
看起来你访问了arr数组末尾以外的几个元素。我的意思是,如果j+1大于或等于n,你就出界了。