STL标准容器中内容的打印技巧
在调试C++代码的过程中经常需要打印容器内容,怎么打印才能更加方便。
1、简单直接的方法
采用索引遍历
for(size_t i = 0; i < container.size(); ++i) { std::cout << container[i] << std::endl; }
或者使用迭代器
for(auto itr = container.begin(); itr != container.end(); ++itr) { std::cout << *itr << std::endl; }
2、高级的打印方法
用for_each和Lamda表达式
for_each (container.begin(), container.end(), [&](const std::string& value){ std::cout << value << std::endl; });
采用ostream_iterator
#include <iterator> #include <algorithm> std::copy(container.begin(), container.end(), std::ostream_iterator<std::string>(std::cout, ","));
除非注明,否则均为[半杯茶的小酒杯]原创文章,转载必须以链接形式标明本文链接