首页 > 解决方案 > 错误:类型向量没有可行的重载运算符 []

问题描述

嗨,我正在尝试练习 c++ 并在解决问题时遇到了一个错误,我在代码中使用了向量,并在通过引用运算符'[]' 在向量中添加两个元素时出现错误

C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> temp;
        int p = 0;
        for (auto i = nums.begin(); i != (nums.end() - 1); ++i) {
            cout<<*i;
            p = nums[i]+nums[i+1];                 //Error is in this line
            if ((p) == target) {
                temp.push_back(i);
                temp.push_back(i + 1);
                return temp;
            }
        }
    }
};

错误:类型向量没有可行的重载运算符 []

标签: c++c++11stl

解决方案


我修复了您的代码,您不能将迭代器与数值混合。

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> temp;
        int p = 0;
        for (auto i = nums.begin(); i != (nums.end() - 1); ++i) {
            cout << *i;
            p = *i + *(i + 1);                 //now code works fine 
            if ((p) == target) {
                temp.push_back(*i);
                temp.push_back(*(i + 1));
                return temp;

            }
        }


    }
};

当您使用迭代器使用循环时,您不应该通过 [] 运算符访问向量,因为迭代器是指向向量元素的指针。只需使用 *i 访问值迭代器指向的值。


推荐阅读