C++ 在 Vector 中查找对象成员值

C++ Find object member value in Vector

本文关键字:对象 成员 查找 Vector C++      更新时间:2023-10-16

我有一个包含两个值的人的结构 - 第一个初始和名字。

有一个这些人物结构的向量。

我需要搜索 Vector 以找到具有匹配的第一个首字母的第一个人,并从该结构中检索名字。

我的研究强调了对 Person 结构使用重载运算符的必要性,但我需要一些指导。

注意:只能使用 Vector 和 find() 算法。无法使用加速。

  #include <stdio.h>
  #include <iostream>
  #include <stdexcept>
  #include <vector>
  #include <algorithm>
  #include <string>
  using namespace std;
  struct person
  {
     char firstInitial;
     string firstName;
     person(const char fi, const string fn)
     {
        firstInitial = fi;
        firstName = fn;
     };
     char getInitial()
     {
        return firstInitial;
     };
     string getName()
     {
        return firstName;
     };
     bool operator==(const person& l, const person& r) const
     {
        return l.firstInitial == r.firstInitial;
     }
  };

  int main (int argc, char *argv[])
  {
     vector<person> myvector;
     vector<person>::iterator itr;
     myvector.push_back(person('j', "john"));
     myvector.push_back(person('s', "steve"));
     myvector.push_back(person('c', "candice"));
     itr = find (myvector.begin(), myvector.end(), itr->getInitial() == 's');
     if (itr != myvector.end())
        cout << "First Name: " << itr->getName() << 'n';
     else
        cout << "NOT Found" << 'n';
  }

1.operator==()应该是一个二进制函数。如果您希望它成为成员函数,它应该采用一个参数,例如:

bool operator==(const person& r) const
{
    return firstInitial == r.firstInitial;
}

或者使其成为非成员函数(将其移出类声明):

bool operator==(const person& l, const person& r)
{
    return l.firstInitial == r.firstInitial;
}

2. std::find希望其第三个参数是要比较的值,您可以将其更改为:

itr = find (myvector.begin(), myvector.end(), person('s', ""));

operator==成员函数只接受一个参数,而不是两个参数。它的工作是将this与作为单个参数传递的类的另一个实例进行比较。

此外,std::find 的第三个参数不是布尔值,而是要在要搜索的序列中查找的对象实例。或者,可以将 lambda 作为第三个参数提供给 std::find_if