c++ - 带有自定义比较器的 std::set_intersection

标签 c++ set-intersection

我在尝试理解使用自定义比较器时 std::set_intersection 的语法。 我正在尝试获取集合 onetwo 的交集,这将导致集合 (intersect) 仅包含元素 f2.

我得到错误:

passing ‘const Foo’ as ‘this’ argument discards qualifiers

#include <set>
#include <string>

struct Foo
{
    std::string str;
};

struct Compare_custom
{
    bool operator () (const Foo & lhs, const Foo & rhs)
    {
        return (lhs.str.size() > rhs.str.size());
    }
};

int main ()
{
    std::set<Foo, Compare_custom> one, two, intersect;

    Foo f1, f2, f3;

    f1.str = "-";
    f2.str = "--";
    f3.str = "---";

    one.insert(f1);
    one.insert(f2);

    two.insert(f2);
    two.insert(f3);

    std::set_intersection(one.begin(), one.end(),
        two.begin(), two.end(),
        intersect.begin(), Compare_custom());
}

我做错了什么?

最佳答案

您错误地为 std::set 使用了 std::set_intersection。试试这个:

std::set_intersection(one.begin(), one.end(),
        two.begin(), two.end(),
        std::inserter(intersect, intersect.begin()), Compare_custom());

关于c++ - 带有自定义比较器的 std::set_intersection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49828583/

相关文章:

sql - 试图了解sql查询中的 "except all"

algorithm - 高效计算 n 组的交集

java - 在 Java 中将两个位集交叉成一个新的位集的最快方法是什么?

C++比较2个字符串列表

r - 列表的多个交集

c++ - 以 vector 作为类成员的对象数组

c++ - 为什么 MinGW 4.9 显示缺少符合标准的正确代码的初始化程序警告

c++ - boost::this_thread::sleep_用于使整个程序休眠

c++ - 从 Poco HTTPClientSession 异步读取

c++ - Qt转换unicode实体