以下是使用Lambda表达式将C++的list转换为map的示例代码:
#include <iostream>
#include <list>
#include <map>
#include <string>
using namespace std;
int main()
{
// 创建一个包含姓名和年龄的list
list<pair<string, int>> people = { {"Alice", 25}, {"Bob", 30}, {"Charlie", 35} };
// 将list转换为map,键为姓名,值为年龄
map<string, int> age_map;
for_each(people.begin(), people.end(), [&age_map](const pair<string, int>& p) { age_map[p.first] = p.second; });
// 输出结果
for (const auto& p : age_map) {
cout << p.first << " is " << p.second << " years old." << endl;
}
return 0;
}
该代码使用Lambda表达式将包含姓名和年龄的list转换为map,其中Lambda表达式使用for_each函数遍历list中的每个元素,并将其添加到map中。最后,使用范围for循环输出map中的每个元素。