Stu*_*urm 0 c++ indexing vector
我已经定义:
const vector<vector<int>> *ElementLines::Quad4 = new vector<vector<int>>
{
{ 0, 1 },
{ 1, 2 },
{ 2, 3 },
{ 3, 0 }
};
Run Code Online (Sandbox Code Playgroud)
稍后,我想迭代一个对象所指向的集合:
for (int j = 0; j < e->LinesIndices->size(); j++)
{
int n1Index = e->LinesIndices[j][0]; //I expect 0 (for j = 0)
int n2Index = e->LinesIndices[j][1]; //I expect 1 (for j= 0)
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不会编译:
no suitable conversion function from "const std::vector<int, std::allocator<int>>" to "int" exists
Run Code Online (Sandbox Code Playgroud)
但是,如果我添加LinesIndices[j][0][0]它确实提供了一个int.我不太明白这里发生了什么.要访问一个向量,我只使用一对方括号[i],这个嵌套的向量向量是不同的?(我希望能够通过使用两对方括号来访问内容).
你的代码没有编译,因为你e->LinesIndices是一个vector<vector<int>>*(即一个指针).
在C++中,就像在C中一样,你可以在指针上使用数组表示法 - a[index]相当于*(a + index).如果指针指向数组的第一个元素,那么这就是您使用该数组的方式.不幸的是,您只能通过分配一个向量new.e->LinesIndices[j]如果j不是0,则访问该指针是非常糟糕的事情(因为您访问没有实际向量的向量).
有两种方法可以解决这个问题.如果你真的想把你的向量保存在堆上,通过new(我希望你delete在某个时候!)分配,你可以在访问之前取消引用指针:
for (int j = 0; j < e->LinesIndices->size(); j++)
{
int n1Index = (*e->LinesIndices)[j][0];
int n2Index = e->LinesIndices[0][j][1]; // This would work too, but I wouldn't recommend it
}
Run Code Online (Sandbox Code Playgroud)
但是,向量中的数据已经在堆上.根据我的个人经验分配一个std::vectorvia new是非常必要的,如果你没有必要在这里有一个指针(这将在很大程度上取决于你使用它的上下文),我建议直接创建矢量(没有指针).如果选择此方法,则需要使用e->LinesIndices.size()而不是e->LinesIndices->size().