【问题标题】:how to print vector of vectors using vector.begin() to vector.end()如何使用vector.begin()到vector.end()打印向量的向量
【发布时间】:2016-02-11 14:55:00
【问题描述】:

取一个int向量的向量,我如何从头到尾打印所有的向量

for(row=v.begin();row!=v.end();row++){
        for(col=row->begin();col!=row->end();col++){
            //cout<<? 
        }
    }

内部for循环应该使用什么来打印每个元素

【问题讨论】:

标签: c++ vector iterator


【解决方案1】:

就我个人而言,我喜欢使用从0size() 的简单for 循环来迭代向量,但这是使用迭代器的方式:

for(vector< vector<int> >::iterator row = v.begin(); row != v.end(); ++row) {
    for(vector<int>::iterator col = row->begin(); col != row->end(); ++col) {
        cout << *col;
    }
}

见:Iteration over std::vector: unsigned vs signed index variable

【讨论】:

  • 使用迭代器进行迭代是首选,因为它可以更快。此外,如果您将 size() 放在 for 循环条件中,它可能会在每次迭代时调用 size(),这是很多额外的函数调用。恕我直言,应该使用基于范围的 for 循环。
  • @songyuanyao 我知道。我正在向回答者评论他说 我喜欢使用从 0 到 size() 的简单 for 循环来迭代向量
  • @NathanOliver 是的,但是当您不非常担心效率时,我认为迭代器在语法上过于冗长(尤其是在 C++98 中)。它使您的代码的可读性降低,IMO,在许多情况下,我更看重可读性而不是效率。
  • typedef 可以很容易地解决这个问题。我也尝试编写可读性代码,除非我怀疑它会损害性能并且多个不必要的函数调用属于此范围。由于很多标准都是基于迭代器的,因此大多数人应该习惯于使用它们并阅读语法。
  • @NathanOliver 为什么它会在循环的每次迭代中调用size(),而不是end()?它们不是都起作用吗?
【解决方案2】:

v.begin() 将迭代器返回到序列的开头
v.end() 将迭代器返回到序列末尾之后的元素

您可以使用这些迭代器遍历您的结构:

for(auto it_row =v.begin(); it_row!=v.end(); it_row++){
    for(auto it_col=it_row->begin();it_col!=it_row->end();it_col++){
        cout<<*it_col<<endl;
    }
}

为了尊重(获取值)您的迭代器,您需要使用以下语法:*it_col

我使用了auto (C++ 11) 而不是显式放置迭代器类型:

vector&lt;vector&lt;int&gt;&gt;::const_iterator it_row = v.begin()
vector&lt;int&gt;::const_iterator it_col = it_row-&gt;begin()

您可以找到有关迭代器的更多详细信息here

【讨论】:

    【解决方案3】:

    如果你使用的是c++11,那么你可以使用基于范围的for循环;

    for (const auto & items : v)
        for (const auto & item : items)
            cout << item;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      相关资源
      最近更新 更多