【发布时间】:2013-06-25 16:55:14
【问题描述】:
有没有办法使用 std::ostream_iterator (或类似的),以便不为最后一个元素放置分隔符?
#include <iterator>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
std::vector<int> ints = {10,20,30,40,50,60,70,80,90};
std::copy(ints.begin(),ints.end(),std::ostream_iterator<int>(std::cout, ","));
}
将打印
10,20,30,40,50,60,70,80,90,
我试图避免尾随分隔符。我要打印
10,20,30,40,50,60,70,80,90
当然,你可以使用循环:
for(auto it = ints.begin(); it != ints.end(); it++){
std::cout << *it;
if((it + 1) != ints.end()){
std::cout << ",";
}
}
但鉴于 C++11 基于范围的循环,跟踪位置很麻烦。
int count = ints.size();
for(const auto& i : ints){
std::cout << i;
if(--count != 0){
std::cout << ",";
}
}
我愿意使用 Boost。我查看了boost::algorithm::join(),但需要将整数复制到字符串,所以它是一个两行。
std::vector<std::string> strs;
boost::copy(ints | boost::adaptors::transformed([](const int&i){return boost::lexical_cast<std::string>(i);}),std::back_inserter(strs));
std::cout << boost::algorithm::join(strs,",");
理想情况下,我只想使用 std::algorithm 并且在范围内的最后一项上没有分隔符。
谢谢!
【问题讨论】:
-
infix_iterator 会回答这个问题吗?
-
迭代到 std::copy 行中的倒数第二个值,而不是 ::end,然后打印最后一项。
-
@Cubbi [infix_iterator][stackoverflow.com/a/3497021/273767] 确实有效。很好,它是代码中 std::ostream_iterator 的替代品。
标签: c++ iostream stl-algorithm