使用带有绑定的boost字符串算法谓词

时间:2012-02-13 11:23:42

标签: c++ boost

编译此示例

#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电话有什么问题?

2 个答案:

答案 0 :(得分:5)

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); });
}

答案 1 :(得分:-1)

如果您的编译器支持某些C ++ 11,则可以使用std :: bind。在C ++ 11中你可以使用std :: placeholders :: _ 1,所以它可能是你的boost :: placeholders :: _ 1。