如何使用 for_each 获取向量中值的索引?
我有以下代码(编译器:MSVC++ 10):
std::vector<float> data;
data.push_back(1.0f);
data.push_back(1.0f);
data.push_back(2.0f);
// lambda expression
std::for_each(data.begin(), data.end(), [](int value) {
// Can I get here index of the value too?
});
在上面的代码片段中我想要的是获取 lambda 表达式内的数据向量中的值的索引。看来 for_each 只接受单个参数函数。使用 for_each 和 lambda 有什么替代方案吗?
I have the following code (compiler: MSVC++ 10):
std::vector<float> data;
data.push_back(1.0f);
data.push_back(1.0f);
data.push_back(2.0f);
// lambda expression
std::for_each(data.begin(), data.end(), [](int value) {
// Can I get here index of the value too?
});
What I want in the above code snippet is to get the index of the value in the data vector inside the lambda expression. It seems for_each only accepts a single parameter function. Is there any alternative to this using for_each and lambda?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
或者,您可以使用 &value - &data[0],尽管它可能会贵一些。
Alternatively, you can use &value - &data[0], although it might be a bit more expensive.
在 C++14 中,感谢 广义 lambda 捕获,您可以执行类似的操作所以:
In C++14 thanks to generalized lambda captures you can do something like so:
我认为您无法捕获索引,但您可以使用外部变量来进行索引,将其捕获到 lambda 中:
这会按预期打印 3,并且
j
保存指数。如果你想要实际的迭代器,你也许可以这样做:
I don't think you can capture the index, but you can use an outer variable to do the indexing, capturing it into the lambda:
This prints 3, as expected, and
j
holds the value of the index.If you want the actual iterator, you maybe can do it similarly:
像这样的东西:
用作:
Something like this:
Used as:
我认为最简单的方法是使用 std::accumulate:
此解决方案适用于任何容器,并且不需要变量或自定义类。
I think that the simplest way is to use
std::accumulate
:This solution works with any container and it don't require a variable or custom classes.
另一种方法 用于枚举的包装迭代器:
必需的标头:
包装迭代器:
枚举重载:
从 James 复制的测试:
我不包括在此处提供偏移量;尽管 EnumerateIterator 中已完全准备好从 0 以外的位置开始。剩下的选择是进行偏移量的类型以及是否为额外参数添加重载或使用默认值。 (没有理由偏移量必须是迭代器的差异类型,例如,如果将其设置为某种与日期相关的类型,并且每次迭代对应于第二天会怎么样?)
Another way to wrap iterators for enumerate:
Required headers:
Wrapping iterator:
Enumerate overloads:
Copied test from James:
I don't include providing an offset here; though it's fully ready in EnumerateIterator to start at otherwise than 0. The choice left is what type to make the offset and whether to add overloads for the extra parameter or use a default value. (No reason the offset has to be the iterator's difference type, e.g. what if you made it some date related type, with each iteration corresponding to the next day?)
罗杰·佩特(Roger Pate)在对我的另一个答案的评论中建议创建一个执行枚举的迭代器包装器。实施起来有点困难。
此迭代器包装器采用值类型为 T 的前向迭代器(称为“内部迭代器”),并将其转换为值类型为pair的前向迭代器。 ,其中
int
是内部迭代器的距离类型。这将非常简单,除了两件事:
std::pair
构造函数通过 const 引用获取其参数,因此我们无法初始化T&
类型的数据成员;我们必须为迭代器创建我们自己的对类型。operator*
需要返回一个引用,operator->
需要返回一个指针),所以该对必须是迭代器的数据成员。由于它包含引用,我们需要一种方法来“重置”它,并且需要延迟初始化它,以便我们可以正确处理结束迭代器。如果T
不可分配,boost::optional
似乎不喜欢它,因此我们将编写自己的简单lazy
>。lazy
包装器:enumerate_iterator
:测试存根:
这已经过最低限度的测试;如果我删除 C++0x 类型特征和aligned_storage,Comeau 和 g++ 4.1 都会接受它(我在这台笔记本电脑上没有更新版本的 g++ 进行测试)。如果您发现任何错误,请告诉我。
我对有关如何改进这一点的建议非常感兴趣。具体来说,我很想知道是否有办法绕过必须使用
lazy
,可以通过使用 Boost 中的某些内容,也可以通过修改迭代器本身。我希望我只是愚蠢,实际上有一种非常简单的方法可以更干净地实现这一点。Roger Pate suggested in a comment to my other answer creating an iterator wrapper that performs the enumeration. Implementing it was a bit of a beating.
This iterator wrapper takes a forward iterator whose value type is
T
(called the "inner iterator") and transforms it into a forward iterator whose value type is apair<int, T&>
, whereint
is the distance type of the inner iterator.This would be quite simple, except for two things:
std::pair
constructor takes its arguments by const reference so we can't initialize a data member of typeT&
; we'll have to create our own pair type for the iterator.operator*
needs to return a reference andoperator->
needs to return a pointer), so the pair needs to be a data member of the iterator. Since it contains a reference, we'll need a way to "reset" it and we'll need it to be lazily initialized so that we can correctly handle end iterators.boost::optional<T>
seems not to like it ifT
is not assignable, so we'll write our own simplelazy<T>
.The
lazy<T>
wrapper:The
enumerating_iterator
:A test stub:
This has been minimally tested; Comeau and g++ 4.1 both accept it if I remove the C++0x type traits and
aligned_storage
(I don't have a newer version of g++ on this laptop to test with). Please let me know if you find any bugs.I'm very interested in suggestions about how to improve this. Specifically, I'd love to know if there is a way around having to use
lazy<T>
, either by using something from Boost or by modifying the iterator itself. I hope I'm just being dumb and that there's actually a really easy way to implement this more cleanly.遵循 C 和 C++ 的标准约定,第一个元素的索引为 0,最后一个元素的索引为 size() - 1。
因此,您必须执行以下操作;-
Following the standard convention for C and C++, the first element has index 0, and the last element has index size() - 1.
So you have to do the following;-
您还可以将结构作为第三个参数传递给 std::for_each 并计算其中的索引,如下所示:
You could also pass a struct as third argument to std::for_each and count the index in it like so:
也许在 lambda 函数中,向其传递一个
int&
而不是值int
,这样您就可以获得地址。 &那么你可以用它来从第一项中推断出你的位置,这行得通吗?不知道
for_each
是否支持引用Maybe in the lambda function, pass it a
int&
instead of valueint
, so you'd have the address. & then you could use that to deduce your position from the first itemWould that work? I don't know if
for_each
supports references