C++用STL容器map和算法find_if实现名表查找
时间: 2024-05-01 11:23:18 浏览: 8
假设我们有一个名单,其中包含每个人的姓名和年龄,我们可以使用STL容器map来存储这些信息。下面是一个示例代码:
```c++
#include <iostream>
#include <map>
#include <algorithm>
#include <string>
using namespace std;
struct Person {
string name;
int age;
};
// 定义比较函数,用于按姓名查找
struct CmpByName {
bool operator() (const Person& lhs, const Person& rhs) const {
return lhs.name < rhs.name;
}
};
int main() {
// 初始化名单
map<Person, int, CmpByName> directory = {
{{"Alice", 25}, 123},
{{"Bob", 30}, 456},
{{"Charlie", 20}, 789}
};
// 查找名为"Bob"的人
auto it = find_if(directory.begin(), directory.end(), [](const auto& pair) {
return pair.first.name == "Bob";
});
// 输出结果
if (it != directory.end()) {
cout << "Name: " << it->first.name << ", Age: " << it->first.age << ", ID: " << it->second << endl;
} else {
cout << "Person not found!" << endl;
}
return 0;
}
```
在上面的代码中,我们首先定义了一个包含姓名和年龄的结构体`Person`,然后定义了一个比较函数`CmpByName`,用于按姓名进行比较。接着,我们使用`map`容器来存储每个人的信息,并将比较函数作为第三个模板参数传递给该容器。最后,我们使用`std::find_if`算法来按姓名查找特定的人,并输出其信息。