向量: 向量与动态数组相同,能够在插入或删除元素时自动调整自身大小,其存储由容器自动处理。将向量转换为字符串的C++程序。 字符串: C++在其定义中有一种方法来表示字符序列作为类的对象。这个类叫做std::string。
null
std::ostringstream :它是一个对字符串进行操作的输出流类。此类的对象使用包含字符序列的字符串缓冲区。可以使用成员str作为字符串对象直接访问此字符序列。
// C++ program transform a vector into // a string. #include <vector> #include <string> #include <algorithm> #include <sstream> #include <iterator> #include <iostream> int main() { std::vector< int > vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); vec.push_back(6); std::ostringstream vts; if (!vec.empty()) { // Convert all but the last element to avoid a trailing "," std::copy(vec.begin(), vec.end()-1, std::ostream_iterator< int >(vts, ", " )); // Now add the last element with no delimiter vts << vec.back(); } std::cout << vts.str() << std::endl; } |
输出:
1, 2, 3, 4, 5, 6
本文由 贾丁·戈亚尔 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END