Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a vector<int> to string [duplicate]

Tags:

c++

string

vector

In C++, what is the simplest way to convert a vector of ints (i.e. vector<int>) to a string ?

like image 441
shn Avatar asked Dec 20 '11 20:12

shn


People also ask

How do you convert a string vector to an int vector?

Using stoi() function Starting with C++11, you can use the stoi function to convert a string to an int, defined in the <string> header file. It throws std::invalid_argument if the string cannot be parsed. However, it can extract the integer value 1 from the strings like 1s .


2 Answers

I usually do it this way...

#include <string> #include <vector>  int main( int argc, char* argv[] ) {     std::vector<char> vec;     //... do something with vec     std::string str(vec.begin(), vec.end());     //... do something with str     return 0; } 
like image 58
Drew Chapin Avatar answered Sep 20 '22 03:09

Drew Chapin


Maybe std::ostream_iterator and std::ostringstream:

#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(4);   vec.push_back(7);   vec.push_back(4);   vec.push_back(9);   vec.push_back(7);    std::ostringstream oss;    if (!vec.empty())   {     // Convert all but the last element to avoid a trailing ","     std::copy(vec.begin(), vec.end()-1,         std::ostream_iterator<int>(oss, ","));      // Now add the last element with no delimiter     oss << vec.back();   }    std::cout << oss.str() << std::endl; } 
like image 32
Fred Larson Avatar answered Sep 19 '22 03:09

Fred Larson