c ++如何在结构向量的一个字段上创建迭代器 [英] c++ how to create iterator over one field of a struct vector
问题描述
我有一个所有原始类型的结构,如下所示:
I have a structure of all primitive types, like so:
struct record {
int field1;
double field2;
}
我有这个结构的实例向量,如下所示:
I have a vector of instances of this struct, like so:
vector<record> records;
是否有可能/创建向量的最佳方式< int> ; :: iterator
将迭代 field1
?
如果我使用数组记录记录[n]
怎么办?我需要看起来像 vector< int> :: iterator
的东西。
Is it possible/what is the best way to create a vector<int>::iterator
that will iterate over field1
?
What about if I used an array record records[n]
? I need something that looks like vector<int>::iterator
.
编辑:我需要的东西是一个 vector< int> :: iterator
。
I need something that IS a vector<int>::iterator
.
推荐答案
你出去了运气好。
vector< int> :: iterator
不是多态 1 。没有地方可以进入并更改指针步长。 vector< int> :: iterator
仅迭代一系列连续 int
对象,并且你的 int
对象不是连续存储的。
vector<int>::iterator
is not polymorphic1. There's no place to reach in and change the pointer step size. vector<int>::iterator
iterates a sequence of contiguous int
objects, only, and your int
objects are not stored contiguously.
这就是为什么所有的C ++标准算法都被模板化来接受迭代器任何类型。如果你使你的函数成为一个接受任意迭代器类型的模板,你可以使用像Snps写的那样的迭代器适配器。
This is why all the C++ standard algorithms are templated to accept iterators of any type. If you make your function a template accepting arbitrary iterator types, you can use an iterator adaptor like the one Snps wrote.
1 相对于指针算术,多态性慢,没有人会使用 std :: vector
如果它没有与普通数组类似的性能
1Polymorphism is slow relative to pointer arithmetic, no one would use std::vector
if it didn't have similar performance to a plain array
这篇关于c ++如何在结构向量的一个字段上创建迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!