用逗号C+打印列表我知道如何在其他语言中这样做,但不知道C+,这是我不得不在这里使用的。我有一套字符串,我要打印在一个列表中,他们需要一个逗号之间的每一个,但不是尾随逗号。例如,在java中,我会使用一个字符串构建器,并在构建字符串之后删除末尾的逗号。如何在C+中实现?auto iter = keywords.begin();for (iter; iter != keywords.end( ); iter++ ){
out << *iter << ", ";}out << endl;我最初尝试插入这个块来完成它(在这里移动逗号打印)if (iter++ != keywords.end())
out << ", ";iter--;我讨厌那些小事把我绊倒。编辑:谢谢大家。这就是为什么我在这里发布这样的东西。这么多好的答案,并以不同的方式处理。在完成了一个学期的Java和程序集(不同的课程)之后,我不得不在4天内完成一个C+项目。我不仅得到了答案,而且有机会思考解决这样一个问题的不同方法。太棒了。
3 回答
拉莫斯之舞
TA贡献1820条经验 获得超10个赞
// infix_iterator.h // // Lifted from Jerry Coffin's 's prefix_ostream_iterator #if !defined(INFIX_ITERATOR_H_) #define INFIX_ITERATOR_H_ #include <ostream> #include <iterator> template <class T, class charT=char, class traits=std::char_traits<charT> > class infix_ostream_iterator : public std::iterator<std::output_iterator_tag,void,void,void,void> { std::basic_ostream<charT,traits> *os; charT const* delimiter; bool first_elem; public: typedef charT char_type; typedef traits traits_type; typedef std::basic_ostream<charT,traits> ostream_type; infix_ostream_iterator(ostream_type& s) : os(&s),delimiter(0), first_elem(true) {} infix_ostream_iterator(ostream_type& s, charT const *d) : os(&s),delimiter(d), first_elem(true) {} infix_ostream_iterator<T,charT,traits>& operator=(T const &item) { // Here's the only real change from ostream_iterator: // Normally, the '*os << item;' would come before the 'if'. if (!first_elem && delimiter != 0) *os << delimiter; *os << item; first_elem = false; return *this; } infix_ostream_iterator<T,charT,traits> &operator*() { return *this; } infix_ostream_iterator<T,charT,traits> &operator++() { return *this; } infix_ostream_iterator<T,charT,traits> &operator++(int) { return *this; } }; #endif
#include "infix_iterator.h"// ...std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));
侃侃尔雅
TA贡献1801条经验 获得超16个赞
for (iter = keywords.begin(); iter != keywords.end(); iter++) { if (iter != keywords.begin()) cout << ", "; cout << *iter;}
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
std::experimental::ostream_joiner
:
#include <algorithm>#include <experimental/iterator>#include <iostream>#include <iterator>int main(){ int i[] = {1, 2, 3, 4, 5}; std::copy(std::begin(i), std::end(i), std::experimental::make_ostream_joiner(std::cout, ", "));}
- 3 回答
- 0 关注
- 452 浏览
添加回答
举报
0/150
提交
取消