c++ - 在 boost::unordered_set 字符串中使用 Lambda 函数 - 不区分大小写

标签 c++ lambda string-comparison case-insensitive unordered-set

目标:需要有 boost::unordered_set 字符串——不区分大小写。 但是这个集合是一个类的成员变量。

如果它不是成员变量,我可以按如下方式创建这个集合。它对我有用。

auto hash= [](const std::string& s) -> size_t
{
    size_t seed = 0;
    //Logic
    return seed;
};

auto equal= [](const std::string& s1, const std::string& s2)
{ 
    return boost::algorithm::iequals(s1, s2, std::locale());
};

typedef boost::unordered_set<std::string, decltype(hash), decltype(equal) > StringSet;

因为我的 boost::unordered_set 是一个类成员,所以我不能像上面那样定义它。

我如何使用 lambda 函数而不是仿函数创建此类成员。

最佳答案

也许这就是您正在寻找的:

https://wandbox.org/permlink/qz8mbCY57BNPbZEU

#include <string>
#include <boost/unordered_set.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/algorithm/string/predicate.hpp>

template <typename H, typename E>
struct my_class_with_member_set {
    boost::unordered_set<std::string, H, E > _set;
    my_class_with_member_set(std::size_t s, H h, E e):_set(s,std::move(h),std::move(e)){}
};

int main(){
    auto hash= [](const std::string& s) -> size_t
    {
        size_t seed = 0;
        //Logic
        return seed;
    };

    auto equal= [](const std::string& s1, const std::string& s2)
    { 
        return boost::algorithm::iequals(s1, s2, std::locale());
    };

    my_class_with_member_set my_class(42,hash,equal);
    my_class._set.insert("foo");
    my_class._set.insert("bar");


    return my_class._set.size();
}

-- 更新--

或:

https://wandbox.org/permlink/UWVV2puGXWXWLqvC

#include <string>
#include <boost/unordered_set.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/algorithm/string/predicate.hpp>

class my_class_with_member_set {
    constexpr static auto hash= [](const std::string& s) -> size_t
    {
        size_t seed = 0;
        //Logic
        return seed;
    };

    constexpr static auto equal= [](const std::string& s1, const std::string& s2)
    { 
        return boost::algorithm::iequals(s1, s2, std::locale());
    };

public:
    boost::unordered_set<std::string, decltype(hash), decltype(equal) > _set;
    my_class_with_member_set(std::size_t s):_set(s,hash,equal){}
};

int main(){
    my_class_with_member_set my_class(42);
    my_class._set.insert("foo");
    my_class._set.insert("bar");


    return my_class._set.size();
}

关于c++ - 在 boost::unordered_set 字符串中使用 Lambda 函数 - 不区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669449/

相关文章:

c++ - 作为子目录添加时,CMake 不构建库

c# - 难以理解特定的 lambda 表达式

c# - linq中的动态排序

objective-c - 检查对象实例的属性是否为 'blank'

php - 字符串比较的行为不同

c++ - 我们什么时候需要将数组的大小作为参数传递

python - 如何在通过 python 扩展访问的 C++ 库中捕获 AddressSanitizer 引发的错误

c++ - 将一个字符串插入另一个字符串......(sprintf)

python - 列表理解中奇怪的 lambda 行为

javascript - 在 JavaScript 中检查字符串是否相等的正确方法是什么?