gpt4 book ai didi

c++ - 类的 unique_copy 无法识别运算符<

转载 作者:行者123 更新时间:2023-11-28 01:18:57 25 4
gpt4 key购买 nike

我无法理解编译器错误消息关于 unique_copy 的含义:

error C2672: 'operator __surrogate_func': no matching overloaded function found

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

最佳答案

为员工重载 == 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; } );

关于c++ - 类的 unique_copy 无法识别运算符<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57548682/

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