C ++:向量到字符串流 [英] C++: vector to stringstream

查看:60
本文介绍了C ++:向量到字符串流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用通用编程将std :: vector转换为std :: stringstream,以及如何实现这一目标?

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?

推荐答案

适应Brian Neal的评论,只有在<< 运算符为中的对象定义了以下内容时,以下内容才有效> std :: vector (在此示例中为 std :: string ).

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

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

这篇关于C ++:向量到字符串流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆