c++ - 使用 std::for_each 迭代和打印 std::map
问题描述
最近,我了解了 STL 类型和模板,作为练习 STL 和习惯使用它的一部分,我们遇到了挑战:
- 迭代一个
std::map<std::string, size_t>
- 打印其内容
限制:
只能使用:
std::vector
,std::map
,std::string
,std::algorithm
,std::functional
无法定义复杂类型或模板
无法使用
. (member access), -> (member access via pointer), * (dereference) operators
不能使用
for, while, do-while nor if-else, switch
和其他条件可以使用
std::for_each
函数模板的其他函数来迭代元素集合没有 lambda
不
std::cout
,,std::cerr
等等std::ostream
。没有自动类型
可以使用其他 STL 模板,只要它们包含在 (1) 中描述的标题中
允许使用这些功能:
void print(const std::string& str)
{
std::cout << str << std::endl;
}
std::string split(const std::pair<std::string, size_t> &r)
{
std::string name;
std::tie(name, std::ignore) = r;
return name;
}
最初,我想用它std::for_each(std::begin(mymap), std::end(mymap), print)
来遍历地图,然后使用打印功能打印出内容。然后我意识到我实际上正在与之合作,std::pair<std::string, size_t>
这让我考虑使用std::bind
和std::tie
分手std::pair
。但是由于我认为我需要在std::for_each
表达式中执行此操作,我怎么能打破std::pair
while 还调用元素上的 print 呢?
我也考虑过使用Structured Binding
,但我不允许使用auto
.
所以,问题是,我如何利用 STL 迭代映射以提取然后使用提供的辅助函数打印出键?显然,如果没有这些限制,挑战将非常容易,但鉴于此,我不知道 STL 中的哪种功能是合适的。
解决方案
我从你的函数中使用了一个 "std::pair& 作为 for_each 第三个参数。
我使用 printf() 打印值。
#include <string>
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
std::string Split(const std::pair<std::string, size_t> &r)
{
std::string name;
std::tie(name, std::ignore) = r;
return name;
}
int main()
{
string name1{ "John" };
string name2{ "Jack" };
std::map<std::string, size_t> sample = { {name1, 31}, {name2, 35} };
static vector<std::string> names;
std::for_each(sample.begin(), sample.end(), [](std::pair<std::string, size_t> pickup)
{
static int i = 0;
names.push_back(Split(pickup));
printf("%s\n", names[i].c_str());
i++;
});
}
推荐阅读
- python - 计算Python中两个链接列的频率
- r - 如何引用不在 data.table 标头中的变量?
- micronaut - Micronaut 控制器错误页面未找到
- javascript - 特定 javascript 实例化模式的正确打字稿定义是什么
- javascript - 如何为用户创建 Dialogflow 登录?
- adobe - 如何根据另一个字段内容隐藏 Adobe Acrobat Pro DC 中的字段
- google-apps-script - 让 Google 表格脚本在后台运行
- windows - 如何在 Windows 批处理文件中运行程序而不等待程序退出?我无法获得当前的 SO 答案
- javascript - 反应原生构建失败
- android - 如何使用 Android TV 画中画