c++ - 按对象属性搜索对象 vector

标签 c++ gcc stl std

我正在尝试找出一种很好的方法来查找 vector 中某个对象的索引 - 通过将字符串与对象中的成员字段进行比较。

像这样:

find(vector.begin(), vector.end(), [object where obj.getName() == myString])

我已经搜索但没有成功 - 也许我不完全了解要查找的内容。

最佳答案

您可以使用 std::find_if用合适的仿函数。在此示例中,使用了 C++11 lambda:

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 支持,仿函数可以工作:

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 对象调用,并返回一个 bool 值。例如,

Type t("Foo"); // assume this means t.getName() is "Foo"
MatchString m("Foo");
bool b = m(t); // b is true

然后你可以将一个实例传递给 std::find

std::vector<Type>::iterator it = find_if(v.begin(), v.end(), MatchString(myString));

关于c++ - 按对象属性搜索对象 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15517991/

相关文章:

c++ - cv::cvtColor 获取错误大小的图像

c++ - 比较两个指针以用于标准算法的正确方法

linux - 尝试包含 -lcrypto 时 RISCV gcc 的编译错误

c++ - 使固定大小的 block 池分配器适应某些 STL 容器

C++限制模板模板中的内部类型

c++ - "Project.exe has triggered a breakpoint"实现多线程后

c++ - 通过未定义的无符号整数读取无符号字符数组是否不安全?

c - 为什么会生成 "might be clobbered..."警告?

gcc - "gcc -x c"和 "gcc -x c++"汇编输出的区别

c++11 - 对<string,string>的删除赋值运算符的g++编译器错误