使用 std::for_each 迭代和打印 std::map

Iterating and printing std::map using std::for_each

本文关键字:std 打印 map 迭代 for 使用 each      更新时间:2023-10-16

最近,我了解了 STL 类型和模板,作为练习 STL 和习惯使用它的一部分,我们遇到了一个挑战:

  1. 循环访问std::map<std::string, size_t>
  2. 打印其内容

限制:

  1. 只能使用:std::vectorstd::mapstd::stringstd::algorithmstd::functional

  2. 无法定义复杂类型或模板

  3. 无法使用. (member access), -> (member access via pointer), * (dereference) operators

  4. 不能使用for, while, do-while nor if-else, switch和其他条件

  5. 可以使用函数模板的std::for_each和其他函数来迭代元素集合

  6. 无λ

  7. 没有std::coutstd::cerrstd::ostream等。

  8. 无自动类型

  9. 可以使用其他 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::bindstd::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++;
});
}