gpt4 book ai didi

c++ - 使用带有绑定(bind)的 boost 字符串算法谓词

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:19 25 4
gpt4 key购买 nike

编译这个例子

#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main(int , char** )
{
vector<string> test;

test.push_back("xtest2");
test.push_back("test3");

ostream_iterator<string> out_it(cout, "\n");

remove_copy_if(test.begin(), test.end(), out_it,
boost::bind(boost::algorithm::starts_with, _1, "x"));
}

因错误而失败

no matching function for call to 
‘bind(<unresolved overloaded function type>, boost::arg<1>&, const char [2])’

使用的bind调用有什么问题?

最佳答案

no matching function for call to
‘bind(<unresolved overloaded function type>, boost::arg<1>&, const char [2])’

所以,...解决<unresolved overloaded function type> :

remove_copy_if(test.begin(), test.end(), out_it, boost::bind(
boost::algorithm::starts_with<std::string, std::string>, _1, "x"));

输出:

$ g++ ./test.cpp ./a.exe
test3

通过多做一些工作,您可以使打字变得不那么难看。以下是一些变体:

#include <boost/bind.hpp>
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

namespace my // for alternative styles
{
static bool starts_with(const std::string& s, const std::string& prefix)
{
return boost::algorithm::starts_with(s, prefix);
}

struct starts_with_s
{
starts_with_s(const std::string& prefix) : _p(prefix) {}
bool operator()(const std::string& s) const {
return boost::algorithm::starts_with(s, _p);
}
private: const std::string _p;
};
}


int main(int , char** )
{
vector<string> test;

test.push_back("xtest2");
test.push_back("test3");

ostream_iterator<string> out_it(cout, "\n");

remove_copy_if(test.begin(), test.end(), out_it,
boost::bind(boost::algorithm::starts_with<std::string, std::string>, _1, "x"));

remove_copy_if(test.begin(), test.end(), out_it,
boost::bind(my::starts_with, _1, "x"));

my::starts_with_s pred("x");
remove_copy_if(test.begin(), test.end(), out_it, pred);

// using c++0x style lambdas
const std::string prefix = "x";
remove_copy_if(test.begin(), test.end(), out_it, [&prefix](const std::string& s)
{ return boost::algorithm::starts_with(s, prefix); });
}

关于c++ - 使用带有绑定(bind)的 boost 字符串算法谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9259616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com