使用另一个向量遍历向量的特定元素

Iterating through specific elements of a vector using another vector

本文关键字:向量 元素 遍历 另一个      更新时间:2023-10-16

假设我有一个字符串向量,定义如下。

std::vector<std::string> names;
names.push_back( "Zero"  );
names.push_back( "One"   );
names.push_back( "Two"   );
names.push_back( "Three" );
names.push_back( "Four"  );
names.push_back( "Five"  );
names.push_back( "Six"   );
names.push_back( "Seven" );
names.push_back( "Eight" );
names.push_back( "Nine"  );

另外,假设我有一个向量来定义要循环遍历的元素:

std::vector< int > indices;
indices.push_back( 0 );
indices.push_back( 5 );
indices.push_back( 6 );
如何根据向

indices量的元素迭代向量names,例如访问名称:"Zero""Five""Six"?我知道那件事:

for( vector<string>::iterator it=names.begin() ; it < names.end(); it++)

遍历所有元素或我们可以找到模式的元素,例如,所有其他元素等。但是,如何迭代没有模式或难以找到模式的元素?如何将一个向量用于另一个向量的迭代?像这样:

for( vector<int>::iterator it=indices.begin() ; it < indices.end(); it++ )
{
     names.at( indices.at( it ) )
     ...
}

你的建议几乎是正确的。与其insdices.at(it),不如取消引用迭代器。但是你可以像这样简单地做到这一点:

for(int index : indices) {
    names[index];
}

或者,如果您无法证明所有names.size()> indices[i] i,则可以使用vector::at

就这么简单:

for( vector<int>::iterator it=indices.begin() ; it != indices.end(); ++it )
{
     names.at( *it );
     names[*it]; // for faster but unvalidated access
     ...
}

注意:++it可以更快(但不能更慢),因此通常在您不关心它是后缀还是前缀形式时使用。 通常也使用it != container.end()因为它更通用(例如,小于随机访问迭代器,但不适用于前向迭代器)。

您还可以

std::for_each 调用与 lambda 一起使用来访问指示(版本 1)此外,您可以将基于范围的 for 循环与 rvalues 一起使用(版本 2)

#include <vector>
#include <algorithm>  
int main()
{
  std::vector<std::string> names;
  names.push_back("Zero");
  names.push_back("One");
  names.push_back("Two");
  names.push_back("Three");
  names.push_back("Four");
  names.push_back("Five");
  names.push_back("Six");
  names.push_back("Seven");
  names.push_back("Eight");
  names.push_back("Nine");
  std::vector< int > indices;
  indices.push_back(0);
  indices.push_back(5);
  indices.push_back(6);
  // version 1
  std::for_each(std::cbegin(indices), std::cend(indices),
    [&](auto &idx) { std::cout << names.at(idx) << "n";});
  // version 2
  for (auto &&idx : indices)
    std::cout << names.at(idx) << "n";
  return 0;
}