簡體   English   中英

C++ 中的 2D 矢量迭代

[英]Iteration in 2D Vector in C++

我是 c++ 的初學者。 如何在 c++ stl 中迭代二維向量?

int main()
{
    vector< vector<int>> vec;
    for(int i=0;i<vec.size();i++
    cout<<vec[i]<<" "<<endl;
}

雖然帶有索引的解決方案肯定是正確的,但以下帶有范圍for循環的變體更現代。 它不太靈活,但僅使用這些值就可以完美地工作並且出錯的機會更少。

int main(){
    std::vector<std::vector<int>> vec;
    // add some data to vec
    for(const auto &v: vec){    // the & is important otherwise you copy the inner vector
        for(const auto &i: v){  
            std::cout << i << ' ';
        }
        std::cout << '\n';
    }
    return 0;
}

如果要修改元素,則必須擺脫const

你可以這樣迭代,

int main()
{
    vector< vector<int>> vec;
    for(int i=0;i<vec.size();i++)
    {
        for(int j=0;j<vec[i].size();j++)
           cout<<vec[i][j]<<" ";
        cout<<endl;
    }
}

您可以像這樣使用基於范圍的 for 循環

std::vector<std::vector<int>> vecOFvec{{1,2},{3,4,5},{6,7,8,9}};

for(const auto& elemOuter:vecOFvec){
    std::cout<<"\n";
    for(const auto& elemInner:elemOuter)
                std::cout<<elemInner<<" ";

}

Output

1 2 
3 4 5 
6 7 8 9

讓您在數組中擁有一個 2D 矩陣

int matt[R][C];

迭代二維數組

for(int r=0; r < R; r++){
   for(int c=0; c<C;c++)
       cout << matt[r][c];
   cout << endl;
}

同樣對於 2D 向量,您首先需要行數

我們通過 vec.size();

然后我們需要列大小

我們通過 vec[0].size() 或 vec[i].size() 得到

這只是表示對應於第 0 行或第 i 行的列的大小

for(int i=0; i< vec.size(); i++){
    for(int j=0; j<vec[i].size(); j++)
        cout << vec[i][j] << " ";
    cout << endl;
}

您可以使用迭代器來迭代向量,但請記住迭代器存儲向量/數組的快照和迭代的開始。 如果向量在 for 循環期間更改其大小,您可能會遇到一些問題

暫無
暫無

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

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