使用 std::for_each 迭代和打印 std::map
Iterating and printing std::map using std::for_each
最近,我了解了 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
和其他函数来迭代元素集合 -
无λ
-
没有
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
的同时调用元素上的打印?
我也考虑过使用Structured Binding
但我不允许使用auto
。
那么,问题是,我如何使用 STL 迭代映射以提取并使用提供的帮助程序函数打印出键?显然,如果没有这些限制,挑战将非常容易,但鉴于此,我不知道STL中的哪种功能是合适的。
我从你的函数中使用了"std::p air&"作为第三个参数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("%sn", names[i].c_str());
i++;
});
}
- 如何使用 std::variant 打印地图键/值?
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 如何打印大于"无符号长长"的"std::bitset"的十进制值?
- main() 中的 std::cout 在调试期间不会在调试控制台中打印任何内容
- 重载 std::字符串运算符+ 用于打印枚举名称
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- std::带有颜色和标题的 clog 包装器无法正确打印整数
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- std::cout 在打印变量与函数表达式时的行为不同
- 使用 std::for_each 迭代和打印 std::map
- 有条件的打印和计数在 std::map 上有限制
- 在瓦尔格林德的泄漏摘要中使用 std::ios::sync_with_stdio(fasle) 打印时获取"still reachable"
- 如何在c++中打印原始std::string/c样式的字符串
- 打印空指针时,std::cout 可以打印 "NULL" 而不是 0 吗?
- C++ - 使用 std::list,如何打印对象的私有成员的链接列表?
- 打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?
- 使用带有 std::cout 的单引号打印字符串实际上打印了数字
- Std::copy 和 std::ostream_iterator 使用重载函数打印值
- 为什么 std::hex 没有特别用字符打印为十六进制?
- std::打印换行时字符串清空