C++:向量到字符串流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3008094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:45:58  来源:igfitidea点击:

C++: vector to stringstream

c++stringstlvectorstringstream

提问by Alerty

I want to know if it is possible to transform a std::vector to a std::stringstream using generic programming and how can one accomplish such a thing?

我想知道是否可以使用泛型编程将 std::vector 转换为 std::stringstream 以及如何完成这样的事情?

回答by Jacob

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;

回答by éric Malenfant

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));