为容器编写打印函数的必要性

Necessity of writing print functions for containers?

本文关键字:函数 必要性 打印      更新时间:2023-10-16

我使用了大约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),您需要一个自定义输出迭代器来用逗号和括号打印pair

您在问题中给出的代码有一个提示,说明为什么它不是标准库的一部分。您的代码使用方括号和逗号(不带空格)来显示映射中的对。其他人可能希望它的格式不同,所以标准委员会的选择是:

  1. 提供大量的格式化选项。
  2. 不提供格式化选项,让每个不喜欢格式化的人自己选择。
  3. 什么都不做,让每个人都滚自己的

他们选择了第三个选项,因为他们知道图书馆的发展将满足人们的特定需求。

怎么样:

#include <iostream>
#include <map>
#include <algorithm>
template <typename K, typename V>
    std::ostream& operator<<(std::ostream& os, const std::pair<K,V>& p)
{
    return os << "[" << p.first << ", " << p.second << "]";
}
template <typename Container>
    std::ostream& operator<<(std::ostream& os, const Container& c)
{
    std::copy(c.begin(), c.end(), 
        std::ostream_iterator<typename Container::value_type>(os, " "));
    return os;
}

你可能也被Boost Spirit Karma迷住了:

#include <boost/spirit/include/karma.hpp>
using boost::spirit::karma::format;
using boost::spirit::karma::auto_;
int main()
{
     std::vector<int> ints(1000);
     std::map<std::string, int> pairs();
     // ...
     std::cout << format(auto_ % " ", ints) << std::endl;
     std::cout << format(('[' << auto_ << ',' << ']') % " ", pairs) << std::endl;
}