[英]C++: vector to stringstream
我想知道是否可以使用泛型编程将std :: vector转换为std :: stringstream,如何才能完成这样的事情?
Adapting Brian Neal's comment, the following will only work if the <<
operator is defined for the object in the std::vector
(in this example, std::string
). 根据Brian Neal的评论,只有在std::vector
为对象定义<<
运算符(在本例中为std::string
)时,以下内容才有效。
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
// Dummy std::vector of strings
std::vector<std::string> sentence;
sentence.push_back("aa");
sentence.push_back("ab");
// Required std::stringstream object
std::stringstream ss;
// Populate
std::copy(sentence.begin(), sentence.end(),std::ostream_iterator<std::string>(ss,"\n"));
// Display
std::cout<<ss.str()<<std::endl;
If the vector's element type supports operator<<, something like the following may be an option: 如果向量的元素类型支持operator <<,则类似以下内容可能是一个选项:
std::vector<Foo> v = ...;
std::ostringstream s;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(s));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.