<分区>
我有一个 std::unique_ptr<std::vector<int>>
我正在尝试使用 []
访问一个元素运算符(operator)。如何访问 std::unique_ptr
中包含的 vector 的特定索引? ?
#include <memory>
#include <vector>
int main()
{
std::unique_ptr<std::vector<int>> x;
x[0] = 1;
}
谢谢
<分区>
我有一个 std::unique_ptr<std::vector<int>>
我正在尝试使用 []
访问一个元素运算符(operator)。如何访问 std::unique_ptr
中包含的 vector 的特定索引? ?
#include <memory>
#include <vector>
int main()
{
std::unique_ptr<std::vector<int>> x;
x[0] = 1;
}
谢谢
最佳答案
你有一个指向 vector 的指针,所以你必须取消引用它
(*x)[0] = 1;
或
x->at(0) = 1;
不过,我很好奇,为什么你需要动态分配一个 std::vector
?该容器已经动态分配了底层数组,所以我只需要 x
成为std::vector<int>
直接。
如果您确实保留一个指向 vector 的指针,至少要确保在使用它之前分配该对象
auto x = std::make_unique<std::vector<int>>();
关于c++ - 不匹配 ‘operator[]’(操作数类型为 ‘std::unique_ptr<std::vector<int>>’ 和 ‘int’),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50175246/