如何从谓词中获取元素索引传递给某些STL算法? [英] How to obtain index of element from predicate passed to some STL algorithm?

查看:117
本文介绍了如何从谓词中获取元素索引传递给某些STL算法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有元素向量和一个掩码数组,我想从向量中提取具有真实对应掩码值的元素来分离向量。为此目的,有没有办法使用 std :: copy_if ?问题是,我在谓词中只有 value ,而不是 iterator ,所以我无法知道实际的索引来解决掩码数组。

Say, I have vector of elements and a mask array, and I want to extract elements from vector with true corresponding mask value to separate vector. Is there a way to use std::copy_if for this purpose? The problem is, I only have value of element inside predicate, not iterator to it, so I cannot know the actual index to address mask array.

我可以直接操作这样的地址:

I can directly manipulate addresses like this:

vector<bool> mask;
vector<int> a, b;
copy_if(a.begin(), a.end(), b.begin(), [&] (int x) -> bool { 
  size_t index = &x - &a[0]; // Ugly...
  return mask[index];
});

然而,我发现这是一个丑陋的解决方案。有没有更好的想法?

However, I find this to be ugly solution. Any better ideas?

更新:另一种可能的解决方案是在掩码上使用外部迭代器:

Update: Another possible solution is to use external iterator on mask:

vector<bool> mask;
vector<int> a, b;
auto pMask = mask.begin();
copy_if(a.begin(), a.end(), b.begin(), [&] (int x) { 
  return *pMask++;
});

但是,此解决方案需要外部命名空间中的其他变量,这仍然是不可取的。

However, this solution requires additional variable in outer namespace which still is not desirable.

推荐答案

好的,经过一番调查后我发现第一个例子是最简单的方法。但是,不应忘记通过(const)引用传递lambda中的值,以便不获取参数的本地副本的地址:

Ok, after a bit of investigation I come out with the first example be the easiest way. However, one should not forget to pass value in lambda by (const) reference for not to take address of local copy of a parameter:

copy_if(a.begin(), a.end(), b.begin(), 
  [&] (const int& x) -> bool {  // <-- do not forget reference here
    size_t index = &x - &a[0];  // Still ugly... but simple
    return mask[index];
  });

这篇关于如何从谓词中获取元素索引传递给某些STL算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆