C++ 使用 copy_if

Hel*_*DoC 2 c++ copy

我是 C++ 新手,正在尝试使用该copy_if函数:

set<Person> people; // contains people objects

set<Person> copyedPeople;

string name = "joe"; // Multiple people with that name

copy_if(people.begin(), people.end(), copyedPeople, Person.getName() == name);
Run Code Online (Sandbox Code Playgroud)

问题出在Person.getName(),它说类型名称不允许?

Jar*_*d42 7

您需要插入器以及有效的谓词:

std::copy_if(people.begin(), people.end(),
             std::inserter(copyedPeople, copyedPeople.end()),
             [](const auto& person){ return person.getName() == name; });
Run Code Online (Sandbox Code Playgroud)

我不知道你的 person 比较器函数,但如果你使用名字,之前的答案最多会返回 1 person。并且std::multiset可能适合与equal_range.