类的unique_copy无法识别运算符<

时间:2019-08-18 22:00:52

标签: c++ stl

我不明白编译器错误消息对unique_copy的含义:

  

错误C2672:“运算符__surrogate_func”:没有匹配的重载   找到功能

std::unique_copy(begin(collection_raw), end(collection_raw), back_inserter(collection_sorted));

我用less运算符提交员工集合,像这样:

struct employee
{
    std::string name;
    std::string address;
};

// Employees comparer
bool operator<(const employee& item1, const employee& item2)
{
    return item1.name < item2.name;
}

该错误消息来自Visual Studio 2019,我不确定这意味着什么。

下面是一个编译的示例,因为我注释掉了std :: unique_copy:

#include <iostream>
#include <vector>
#include <list>
#include <algorithm>

struct employee
{
    std::string name;
    std::string address;
};

// Employee comparer
bool operator<(const employee& item1, const employee& item2)
{
    return item1.name < item2.name;
}

// Copy the raw vector of employees into a list of sorted and unique employees
void copy_uniq_elements(std::vector<employee>& collection_raw, std::list<employee>& collection_sorted)
{
    // use operator< to order items
    std::sort(begin(collection_raw), end(collection_raw));

    // Don't copy adjacent equal elements
    // error C2672:  'operator __surrogate_func': no matching overloaded function found
    // std::unique_copy(begin(collection_raw), end(collection_raw), back_inserter(collection_sorted));
}

int main()
{
    std::vector<employee> staff { {"Bob", "11 rue de longueil"},
                                  {"Arnold", "22 rue de la retraite"},
                                  {"Gilbert", "33 rue de belle-humeur"},
                                  {"Xavier", "11 rue de longueil"} };

    std::list<employee> staff_sorted;
    copy_uniq_elements(staff, staff_sorted);

    for (const auto item : staff_sorted)
    {
        std::cout << item.name << std::endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:2)

为员工超载== operator

bool operator==(const employee& item1, const employee& item2)
{
    // something.
}

或将二进制谓词传递给std :: unique_copy

std::unique_copy(begin(collection_raw), end(collection_raw), back_inserter(collection_sorted), 
         [] (auto& b, auto& c) { return b.name == c.name; } );