gpt4 book ai didi

c++ - 为容器编写打印函数的必要性?

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:09 28 4
gpt4 key购买 nike

我使用了大约 6 种不同的 C++ 容器。我开始编写打印函数来输出容器内容。这是必要的吗?我会认为这是 C++ 库的一部分吗?

  void print_list(const list<int>& list_int)
{
for (list<int>::const_iterator it = list_int.begin(); it != list_int.end(); it++) cout << *it << " ";
}
void print_um(const unordered_map<int, double>& map_int_d)
{
for(unordered_map<int, double>::const_iterator it = map_int_d.begin(); it != map_int_d.end(); ++it)cout << "[" << it->first << "," << it->second << "] ";
}

最佳答案

它不是库的一部分,但使用提供的工具很容易编写:

C c; // Where C is a container type
std::copy(
c.begin(), c.end()
, std::ostream_iterator< C::value_type >( cout, " " )
);

对于元素是pair(比如map,我相信是unordered_map)的容器,你需要一个自定义的输出迭代器来打印带有逗号和括号的

关于c++ - 为容器编写打印函数的必要性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7855941/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com