gpt4 book ai didi

c++ - std::find_if 映射到对象

转载 作者:行者123 更新时间:2023-11-28 04:17:27 35 4
gpt4 key购买 nike

对于从 find_if 到对象的映射指针,我应该使用示例 1 还是示例 2哪个最好?

struct test {
INT id
}

std::vector<std::shared_ptr<test>> vec;

int ID = 75;

auto obj = std::find_if(vec.begin(), vec.end(), [&ID](std::shared_ptr<test>& r){
return r->id == ID;
});

if ( obj != vec.end() ) {
// example 1
std::shared_ptr<test> example1 = (*obj);

// example 2 by reference
std::shared_ptr<test>& example2 = (*obj);
}

最佳答案

如果您不打算在调用 find_if 和使用 shared_ptr 之间修改 vec,则将元素引用为在 example2 中避免对引用计数进行不必要的调整。如果您不能确定是这种情况,请按值复制 shared_ptr,如 example 中所示。

关于c++ - std::find_if 映射到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56304730/

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