我正在尝试遍历一个对象 vector ,然后选择一个与特定 ID 匹配的对象。下面的示例将打印与 ID 匹配的第一个对象,但我如何打印或选择与相同 ID 匹配的几个对象?我尝试使用 while 循环,它会起作用,但是因为我每次都必须增加迭代器,所以我总是会得到“段错误”。
it = find_if(database.begin(), database.end(), [&id](cd &c) {
return c.getId() == id;
});
int index = std::distance(database.begin(), it); //finding index of the object
database[index].print(); //prints everything from the object
最佳答案
有几种选择,包括:
for (auto& c: database) {
if (c.getId() == id) {
c.print();
}
}
或
auto next_it = [&](auto beg) {
return std::find_if(beg, database.end(),
[&id](cd &c) {
return c.getId() == id;
});
};
for (auto it = next_it(database.begin()); it != database.end(); it = next_it(it + 1)) {
it->print();
}
或(使用 range-v3 )
for (auto& c: database | ranges::filter([&](const auto& c){ return c.getId() == id; })) {
c.print();
}
关于C++ 如何使用 lambda find_if 选择多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47177129/