为容器编写打印函数的必要性
Necessity of writing print functions for containers?
我使用了大约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
。
您在问题中给出的代码有一个提示,说明为什么它不是标准库的一部分。您的代码使用方括号和逗号(不带空格)来显示映射中的对。其他人可能希望它的格式不同,所以标准委员会的选择是:
- 提供大量的格式化选项。
- 不提供格式化选项,让每个不喜欢格式化的人自己选择。
- 什么都不做,让每个人都滚自己的
他们选择了第三个选项,因为他们知道图书馆的发展将满足人们的特定需求。
怎么样:
#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;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 实现纯虚函数的必要性是什么
- 视觉 C++当我们在基类中使函数成为纯虚拟时,那么在子类中再次使相同的函数虚拟的必要性是什么
- at()函数相对于get(ch)的必要性
- 为容器编写打印函数的必要性
- 前向声明模板函数的必要性