c++ - 错误:类型向量没有可行的重载运算符 []
问题描述
嗨,我正在尝试练习 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;
}
}
}
};
错误:类型向量没有可行的重载运算符 []
解决方案
我修复了您的代码,您不能将迭代器与数值混合。
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 访问值迭代器指向的值。
推荐阅读
- webview - xamarin 表单 WebView 中的 Cookie
- ios - 在 GPU 和 UIActivityIndicator 上使用 CoreImage
- perforce - 在 Perforce 中,如何将流中的文件移动到不同的仓库?
- netsuite - 创建发票后在客户记录中设置字段值
- android - 如何让recyclerview加载所有itemviews
- notepad++ - 记事本++中包含符号的单词前的新行
- c++ - 编写构造函数/析构函数是一种好习惯吗?
- python-3.x - 如果我在带括号的列表中有重复项,我该怎么办
- adobe-brackets - 括号实时预览突然不工作
- java - 如何在我的 Google Glass 应用中录制视频?