簡體   English   中英

訪問向量 <vector<int> &gt;元素

[英]Accessing vector<vector<int>> elements

我定義了:

const  vector<vector<int>> *ElementLines::Quad4 = new vector<vector<int>>
{
    { 0, 1 },
    { 1, 2 },
    { 2, 3 },
    { 3, 0 }
};

稍后,我要遍歷對象指向的那個集合:

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)
        }

上面的代碼無法編譯:

no suitable conversion function from "const std::vector<int, std::allocator<int>>" to "int" exists  

但是,如果我添加LinesIndices[j][0][0]則確實可以提供一個int值。 我不太了解這里發生了什么。 要訪問向量,我只使用一對方括號[i] ,此向量嵌套向量有何不同? (我希望能夠通過使用兩對方括號來訪問內容)。

您的代碼未編譯,因為您的e->LinesIndicesvector<vector<int>>* (即指針)。

在C ++中,就像在C中一樣,您可以在指針上使用數組符號-a a[index]等效於*(a + index) 如果您的指針指向數組的第一個元素,那正是您使用該數組的方式。 不幸的是,您只有一個通過new分配的向量。 如果j不為0,則通過e->LinesIndices[j]訪問該指針是一件很糟糕的事情(因為在沒有實際矢量的情況下訪問了一個矢量)。

有兩種方法可以解決此問題。 如果您真的想將向量保留在通過new分配的堆上(我希望您在某個時候deletedelete !),則可以在訪問它之前取消引用該指針:

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
}

但是,向量中的數據已經在堆上。 根據我的個人經驗,通過new分配std::vector幾乎是沒有必要的,並且如果您不必在這里有一個指針(這在很大程度上取決於您使用它的上下文),我建議直接創建向量(無指針)。 如果選擇此方法,則需要使用e->LinesIndices.size()而不是e->LinesIndices->size()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM