How to transform a vector int into a string?
What about:
std::stringstream result;
std::copy(my_vector.begin(), my_vector.end(), std::ostream_iterator<int>(result, " "));
Then you can pass the pointer from result.str().c_str()
Convert a vector int to a string
Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++.
You could use a stringstream
...
#include <sstream>
//...
std::stringstream ss;
for(size_t i = 0; i < v.size(); ++i)
{
if(i != 0)
ss << ",";
ss << v[i];
}
std::string s = ss.str();
You could also make use of std::for_each
instead.
How to convert a vector int to string in C++
That code is only needed if you want to add a delimiter after every inserted integer, but even then it doesn't have to be that complicated. A simple loop and the use of to_string
is far more readable:
std::string str;
for (int i = 0; i < vec.size(); ++i) {
str += std::to_string(vec[i]);
if (i+1 != vec.size()) { // if the next iteration isn't the last
str += ", "; // add a comma (optional)
}
}
Converting a vector int to string
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;
}
Convert Vector int to String
std::vector<int> data = {104, 97, 104, 97};
std::string actualword;
char ch;
for (int i = 0; i < data.size(); i++) {
ch = data[i];
actualword += ch;
}
convert vector string TO vector int C++, Win32
Try this:
std::vector<std::string> DataNumbers;
// Fill DataNumbers
std::vector<int> intNumbers;
for (int i=0; i<= 5; i++)
{
int num = atoi(DataNumbers.at(i).c_str());
intNumbers.push_back(num);
}
How do I convert vectors of various types to std::string?
What if I wanted to create a polymorphic
toString
that works withvector<class A>
andvector<vector<class A>
? How would I go about this?
Yes it is possible in c++17, by the cobination of if constexpr
feature and a recursive function template (i.e. making the toString
as recursive function template).
Before jumping into the generic function template, your class A
needs to implement operator<<
overload so-that std::ostringstream::operator<<
can make use of it. For instance, lets consider
struct A
{
char mChar;
// provide a overload for operator<< for the class!
friend std::ostream& operator<<(std::ostream& out, const A& obj) /* noexcept */ {
return out << obj.mChar;
}
};
Now the toString
function would look like something as follows:
#include <type_traits> // std::is_floating_point_v, std::is_integral_v, std::is_same_v
// std::remove_const_t, std::remove_reference_t
template<typename Type>
inline static constexpr bool isAllowedType = std::is_floating_point_v<Type>
|| std::is_integral_v<Type>
|| std::is_same_v<A, Type>;
//^^^^^^^^^^^^^^^^^^^ --> struct A has been added to the
// allowed types(i.e types who has operator<< given)
template<typename Vector>
std::string toString(const Vector& vec) /* noexcept */
{
std::ostringstream stream;
// value type of the passed `std::vector<Type>`
using ValueType = std::remove_const_t<
std::remove_reference_t<decltype(*vec.cbegin())>
>;
// if it is allowed type do concatenation!
if constexpr (isAllowedType<ValueType>)
{
for (const ValueType& elem : vec)
stream << elem << " ";
stream << '\n';
return stream.str();
}
else
{
// otherwise do the recursive call to toString
// for each element of passed vec
std::string result;
for (const ValueType& innerVec : vec)
result += toString(innerVec);
return result; // return the concatenated string
}
}
Now you can call the toString
to the std::vector<std::vector<A>>
as well as std::vector<A> aObjs
, and to the std::vector< /* primitive types */ >
too.
(See Complete Demo Online Live)
Do I just provide at least one specialization of
toString
for that type? Does the template mechanism sort all this out?
Template specialization is another option too. However, if you have access to C++17, I would suggest the above manner, which will sort all of the types you provided in the question.
Convert vector double to vector string ( elegant way )
There are many ways, but a standard solution is to use std::transform
with a lambda using std::to_string
for the conversion :
std::transform(std::begin(doubleVec),
std::end(doubleVec),
std::back_inserter(doubleStr),
[](double d) { return std::to_string(d); }
);
And you can wrap that in a function template to make it work with any Standard compliant container :
template<class IteratorIn, class IteratorOut>
void to_string(IteratorIn first, IteratorIn last, IteratorOut out)
{
std::transform(first, last, out,
[](typename std::iterator_traits<IteratorIn>::value_type d) { return std::to_string(d); } );
}
Or in C++14, with a generic lambda :
template<class IteratorIn, class IteratorOut>
void to_string(IteratorIn first, IteratorIn last, IteratorOut out)
{
std::transform(first, last, out, [](auto d) { return std::to_string(d); } );
}
And call it with any container (i.e. it works with std::list<int>
, for instance) :
to_string(std::begin(doubleVec), std::end(doubleVec), std::back_inserter(doubleStr));
Notes :
- If you don't have a C++11 compiler, write your own
to_string
function template :
Example:
template<class T>
std::string my_to_string(T v)
{
std::stringstream ss;
ss << v;
return ss.str();
}
And use it in a similar way :
std::transform(doubleVec.begin(),
doubleVec.end(),
std::back_inserter(doubleStr),
my_to_string<double> );
- You should
reserve()
the memory in the output vector to avoid reallocations duringstd::transform()
:
e.g. do this :
std::vector<std::string> stringVec;
stringVec.reserve(v.size()); // reserve space for v.size() elements
Live demo
Related Topics
Deprecation of the Static Keyword... No More
Representing 128-Bit Numbers in C++
Constexpr If and Static_Assert
Assigning Parsers to Auto Variables
Standard Library Sort and User Defined Types
What Is the Worst Real-World Macros/Pre-Processor Abuse You'Ve Ever Come Across
Using Scanf() in C++ Programs Is Faster Than Using Cin
Confused When Boost::Asio::Io_Service Run Method Blocks/Unblocks
Why Is 'Std::Move' Named 'Std::Move'
When to Pass by Reference and When to Pass by Pointer in C++
Strongly Typed Using and Typedef