你可以向谓词传递一个附加参数吗? [英] Can you pass an additional parameter to a predicate?

查看:125
本文介绍了你可以向谓词传递一个附加参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过滤一个向量,使其只包含一个特定的值。

I'm trying to filter a vector so it contains only a specific value.

例如。确保向量只包含值abc的元素。

e.g. Make sure the vector only contains elements of the value "abc."

现在,我试图用 remove_copy_if

使用std算法时,是否有任何方法可以向谓词传递一个附加参数?

Is there any way to pass an additional parameter to a predicate when using one of std's algorithms?

std::vector<std::string> first, second;
first.push_back("abc");
first.push_back("abc");
first.push_back("def");
first.push_back("abd");
first.push_back("cde");
first.push_back("def");

std::remove_copy_if(first.begin(), first.end(), second.begin(), is_invalid);

我希望将以下函数作为谓词传递,但似乎更有可能结束比较 remove_copy_if 和下一个检查的当前值。

I'm hoping to pass the following function as a predicate but it seems more likely that this would just end up comparing the current value being examined by remove_copy_if and the next.

bool is_invalid(const std::string &str, const std::string &wanted)
{
   return str.compare(wanted) != 0;
}

我有一种感觉,我可能接近这个错误,所以任何建议

I have a feeling I'm probably approaching this wrong so any suggestions would be appreciated!

感谢

推荐答案

p>

Define a functor instead:

struct is_invalid
{
    is_invalid(const std::string& a_wanted) : wanted(a_wanted) {}
    std::string wanted;
    bool operator()(const std::string& str)
    {
        return str.compare(wanted) != 0;
    }
};

std::remove_copy_if(first.begin(),
                    first.end(),
                    second.begin(),
                    is_invalid("abc"));

或如果C ++ 11使用lambda:

or if C++11 use a lambda:

std::string wanted("abc");
std::remove_copy_if(first.begin(), first.end(), second.begin(), 
    [&wanted](const std::string& str)
    {
        return str.compare(wanted) != 0;
    });

注意输出向量 second 必须在调用 remove_copy_if()之前具有元素

Note that the output vector, second, must have elements before the call to remove_copy_if():

// Create 'second' after population of 'first'.
//
std::vector<std::string> second(first.size());

std::string wanted = "abc";
int copied_items    = 0;
std::remove_copy_if( first.begin(), first.end(), second.begin(),
    [&wanted, &copied_items](const std::string& str) -> bool
    {
        if (str.compare(wanted) != 0) return true;
        copied_items++;
        return false;
    });
second.resize(copied_items);

复制函数谓词需要更多的努力来保留 copied_items 信息。请参阅在C ++中通过引用传递std algos谓词了解建议的解决方案。

As functor predicates are copied more effort is required to retain the copied_items information. See Pass std algos predicates by reference in C++ for suggested solutions.

这篇关于你可以向谓词传递一个附加参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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