可能重复:
请勿在最后一个数字后打印空格
使用逗号C++打印列表
#include <vector>
#include <iostream>
#include <sstream>
#include <boost/foreach.hpp>
using namespace std;
int main()
{
vector<int> VecInts;
VecInts.push_back(1);
VecInts.push_back(2);
VecInts.push_back(3);
VecInts.push_back(4);
VecInts.push_back(5);
stringstream ss;
BOOST_FOREACH(int i, VecInts)
{
ss << i << ",";
}
cout << ss.str();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这打印出来:1,2,3,4,5,
但是我想要:1,2,3,4,5
我怎样才能以优雅的方式实现这一目标?
我看到我对"优雅"的含义有些困惑:例如,我的循环中没有减慢"if-clause"的速度.想象一下向量中的100.000个条目!如果这就是你要提供的全部内容,我宁愿在完成循环后删除最后一个逗号.