【发布时间】:2020-03-19 19:09:30
【问题描述】:
这里是 C++ 新手。我有一个指针变量类型vector,我通过m 将其初始化为n,其中n 和m 是int 作为输入。这是我初始化它的方式。
std::vector<std::vector<int>>* memo; // This is as a member.
void test(int m, int n) {
memo = new std::vector<std::vector<int>>(m, *new std::vector<int>(n, 0)); // This is inside a method.
}
稍后,我尝试分配某个元素。
int ans = 5; // In my actual code, it's something else, but I'm just simplifying it.
memo[i][j] = ans; // This gives an error.
我以为我只需要尊重它,因为现在它是一个指针类型。所以我把它改成了这样:
*memo[i][j] = ans;
但是现在我遇到了一个新错误:
C++ no operator matches these operands operand types are: * std::vector<int, std::allocator<int>>
为什么这不起作用,我怎样才能使它起作用?
【问题讨论】:
-
您可能不需要
std::vector<T>*类型,而是std::vector<T>类型。 C++ 有时很难,但并非不可能正确学习。放弃指针,您就可以开始了。 -
几乎没有理由拥有指向容器的指针。更糟糕的是,由于
*new std::vector<int>(n, 0),您将遇到内存泄漏。您是否来自必须使用new创建对象的 Java 或 C# 背景?在 C++ 中,您不必这样做。我建议你投资a good book or two。 -
至于
*memo[i][j]的问题,由于operator precedence等于*(memo[i][j]),开头不正确(memo是指针)。您需要使用(*memo)[i][j]。但正如我已经说过的,没有指针开始,问题就消失了。