【问题标题】:Error: No viable overloaded operator[] for type vector<int>错误:对于类型 vector<int> 没有可行的重载运算符 []
【发布时间】:2021-11-03 15:40:48
【问题描述】:

您好,我正在尝试练习 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;
            }
        }
    }
};

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

【问题讨论】:

  • i 是一个迭代器,而不是一个索引,你可能想要p = *i + *(i + 1);
  • 顺便说一句,如果找不到,您的函数不会返回。
  • std::adjacent_find(带有自定义谓词)可能会有所帮助。
  • 感谢您的帮助

标签: c++ c++11 stl


【解决方案1】:

i 是一个迭代器,而不是一个索引,所以你根本不需要[]

class Solution {
public:
    std::vector<int> twoSum(std::vector<int>& nums, int target) {
        for (auto i = nums.begin(); i != (nums.end() - 1); ++i) {
            std::cout<<*i;
            if ((*i + *(i + 1)) == target) {
                return { *i, *(i + 1) };
            }
        }
        throw std::runtime_error("no solution found");
    }
};

但是,您可以使用现有的std::adjacent_find

,而不是自己编写循环
class Solution {
public:
    std::vector<int> twoSum(std::vector<int>& nums, int target) {
        auto i = std::adjacent_find(nums.begin(), nums.end(), [target](int a, int b) { 
            std::cout << a;
            return (a + b) == target; 
        });
        if (i != nums.end()) {
            return { *i, *(i + 1) };
        }
        throw std::runtime_error("no solution found");
    }
};

【讨论】:

    【解决方案2】:

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

    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 来访问值迭代器指向的值。

    【讨论】:

    • 通常,评论不同步,//Error is in this line 不再准确。
    • 有没有什么办法可以得到指向的迭代器的索引号。
    • 我认为它需要你稍微改变你的 for 循环,因为我怀疑迭代器是否支持它。你可以只做基本的 for (int i = 0; i
    猜你喜欢
    • 1970-01-01
    • 2015-06-24
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 2015-11-19
    • 2015-12-24
    • 2013-01-03
    相关资源
    最近更新 更多