如何很好地输出分隔的字符串列表? [英] How to nicely output a list of separated strings?
本文介绍了如何很好地输出分隔的字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,当我不得不显示一个单独的字符串列表时,我是这样做的:
Usually, when I had to display a list of separated strings, I was doing something like:
using namespace std;
vector<string> mylist; // Lets consider it has 3 elements : apple, banana and orange.
for (vector<string>::iterator item = mylist.begin(); item != mylist.end(); ++item)
{
if (item == mylist.begin())
{
cout << *item;
} else
{
cout << ", " << *item;
}
}
哪些输出:
apple, banana, orange
我最近发现了 std :: ostream_iterator
,如果发现真的很好用。
I recently discovered std::ostream_iterator
which if found really nice to use.
但是使用下面的代码: / p>
However with the following code:
copy(mylist.begin(), mylist.end(), ostream_iterator<string>(cout, ", "));
如果获得:
apple, banana, orange,
几乎完美, c $ c>,。有没有一种优雅的方式来处理特殊的第一(或最后)元素情况,并具有相同的输出比第一个代码,没有它的复杂性?
Almost perfect, except for the extra ,
. Is there an elegant way to handle the special "first (or last) element case" and to have the same output than the first code, without its "complexity" ?
推荐答案
虽然不是std:
cout << boost::algorithm::join(mylist, ", ");
编辑:没问题:
cout << boost::algorithm::join(mylist |
boost::adaptors::transformed(boost::lexical_cast<string,int>), ", "
);
这篇关于如何很好地输出分隔的字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文