使用另一个向量遍历向量的特定元素
Iterating through specific elements of a vector using another vector
假设我有一个字符串向量,定义如下。
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;
}
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 在 C++ 中输出枚举类类型的向量元素
- 用向量的向量元素初始化向量的空向量
- 为什么不允许使用可变长度数组作为向量元素?
- 在函数中传递向量元素
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- 返回向量元素的 l 值的正确方法是什么?
- 当向量增长时,指向向量元素的C++指针是否无效
- 如何在C++中从一个向量元素减去std::unorderede_map向量元素并更新它
- C++:向量元素赋值导致访问冲突
- 将向量元素与字符串元素进行比较,而不初始化向量
- 从2D矢量中找出最小尺寸的向量元素的更好方法
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 使用递归C++向量元素的总和
- 如何查找为数组中的最低值编制索引的向量元素
- 限制指针访问STL ::向量元素
- 访问索引指向向量元素时的seg故障 - 做错了什么
- 如何使用指针访问向量元素的各个元素
- 向量元素数据损坏了Find()操作
- 将字符值分配给向量元素.C