C++:向量到字符串流

发布于 2024-09-05 03:57:15 字数 95 浏览 5 评论 0原文

我想知道是否可以使用通用编程将 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨后彩虹 2024-09-12 03:57:15

改编 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;

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;
无所谓啦 2024-09-12 03:57:15

如果向量的元素类型支持运算符<<,则可以选择如下所示:

std::vector<Foo> v = ...;
std::ostringstream s;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(s));

If the vector's element type supports operator<<, something like the following may be an option:

std::vector<Foo> v = ...;
std::ostringstream s;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(s));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文