不匹配“operator[]”(操作数类型为“std::unique_ptr<std::vector<int> >”和“int”)
no match for ‘operator[]’ (operand types are ‘std::unique_ptr<std::vector<int> >’ and ‘int’)
我有一个 std::unique_ptr<std::vector<int>>
,我正在尝试使用 []
运算符访问一个元素。如何访问 std::unique_ptr
中包含的向量的特定索引?
#include <memory>
#include <vector>
int main()
{
std::unique_ptr<std::vector<int>> x;
x[0] = 1;
}
谢谢
你有一个指向向量的指针,所以你必须取消引用它
(*x)[0] = 1;
或
x->at(0) = 1;
不过我很好奇,为什么需要动态分配一个std::vector
?该容器已经动态分配了底层数组,所以我只需要 x
直接成为 std::vector<int>
。
如果您保留指向向量的指针,至少确保在使用它之前分配对象
auto x = std::make_unique<std::vector<int>>();
我有一个 std::unique_ptr<std::vector<int>>
,我正在尝试使用 []
运算符访问一个元素。如何访问 std::unique_ptr
中包含的向量的特定索引?
#include <memory>
#include <vector>
int main()
{
std::unique_ptr<std::vector<int>> x;
x[0] = 1;
}
谢谢
你有一个指向向量的指针,所以你必须取消引用它
(*x)[0] = 1;
或
x->at(0) = 1;
不过我很好奇,为什么需要动态分配一个std::vector
?该容器已经动态分配了底层数组,所以我只需要 x
直接成为 std::vector<int>
。
如果您保留指向向量的指针,至少确保在使用它之前分配对象
auto x = std::make_unique<std::vector<int>>();