C++ 在 Vector 中查找对象成员值
C++ Find object member value in Vector
我有一个包含两个值的人的结构 - 第一个初始和名字。
有一个这些人物结构的向量。
我需要搜索 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
。
相关文章:
- 指向设备对象成员的指针
- 访问由unique_ptr传递的对象成员
- 引用对象成员函数的成员函数
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- Lua C API - 从C++分配和使用类的对象成员
- Rapidjson 遍历并获取复杂 JSON 对象成员的值
- 类对象成员变量在调用函数时不会更改
- 对象成员变量还是继承
- C++多态性:有没有办法找到对象成员函数的地址?
- 重载对象成员的比较运算符
- 获取未初始化对象成员的地址是否定义良好?
- 在优先级队列被推送到队列后,如何编辑对象成员
- 为什么在这里调用析构函数,以及在调用该对象析构函数后如何调用对象成员函数?
- 通过 std::bind 从对象成员检索值
- 保留对象成员变量的本地副本
- 有没有办法为静态对象成员定义一个符合开关标准的常量?
- 没有默认构造函数的对象成员的 wig setter
- 对象成员数组C++默认初始化
- 如何在数组中添加对象成员
- 使用聚合创建和关联两个不同的对象成员