Search a vector of objects by object attribute(按对象属性搜索对象向量)
问题描述
我试图找出一种在向量中查找某个对象的索引的好方法 - 通过将字符串与对象中的成员字段进行比较.
I'm trying to figure out a nice way to find the index of a certain object in a vector - by comparing a string to a member field in the object.
像这样:
find(vector.begin(), vector.end(), [object where obj.getName() == myString])
我搜索没有成功 - 也许我不完全明白要寻找什么.
I have searched without success - maybe I don't fully understand what to look for.
推荐答案
您可以使用 std::find_if
带有合适的函子.在此示例中,使用了 C++11 lambda:
You can use std::find_if
with a suitable functor. In this example, a C++11 lambda is used:
std::vector<Type> v = ....;
std::string myString = ....;
auto it = find_if(v.begin(), v.end(), [&myString](const Type& obj) {return obj.getName() == myString;})
if (it != v.end())
{
// found element. it is an iterator to the first matching element.
// if you really need the index, you can also get it:
auto index = std::distance(v.begin(), it);
}
如果您没有 C++11 lambda 支持,函子可以工作:
If you have no C++11 lambda support, a functor would work:
struct MatchString
{
MatchString(const std::string& s) : s_(s) {}
bool operator()(const Type& obj) const
{
return obj.getName() == s_;
}
private:
const std::string& s_;
};
这里,MatchString
是一种类型,它的实例可以用单个 Type
对象调用,并返回一个布尔值.例如,
Here, MatchString
is a type whose instances are callable with a single Type
object, and return a boolean. For example,
Type t("Foo"); // assume this means t.getName() is "Foo"
MatchString m("Foo");
bool b = m(t); // b is true
然后你可以将一个实例传递给 std::find
then you can pass an instance to std::find
std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString));
这篇关于按对象属性搜索对象向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按对象属性搜索对象向量


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01