簡體   English   中英

錯誤:'operator+' 操作數類型不匹配是 'std::vector<int> c++ 中的 ' 和 'int'</int>

[英]Error: no match for 'operator+' operand types are 'std::vector <int>' and 'int' in c++

錯誤:在 c++ 中,“operator+”操作數類型不匹配“std::vector <int>”和“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:: std::vector中沒有 operator+ 重載。 您想要的是v.begin()+h+1用於第一個,而v.begin()+n用於第二個以獲得迭代器。 vector::iterator具有operator+operator++重載,因此它可以接受索引值。

提示,請記住 C++ 具有從零開始的索引。 所以只能通過 0 到 9 之間的索引訪問大小為 10 的向量! 確保在代碼中更正該錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM