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.
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);
}
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;
}
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)
}
}
How to turn an integer into vector and then turn that vector into string in C++
Here you are:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <iterator>
int main() {
int n;
std::cin >> n;
std::vector<int> split(static_cast<int>(std::log10(n)) + 1);
auto royal_10 = split.rbegin();
auto cpy{ n };
do {
*royal_10++ = cpy % 10;
} while ((cpy /= 10) != 0);
std::string ret;
ret.reserve(split.size());
std::transform(split.cbegin(), split.cend(), std::back_inserter(ret),
[](int const dig) { return dig + '0'; });
return 0;
}
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.
Save integers from string to vector
I found a way to solve this.
#include <iostream>
#include <string>
#include <vector>
std::vector < int > extract_numbers(std::string s) {
std::vector < int > vek;
for (int i = 0; i < s.length(); i++) {
std::string word;
while (s[i] == ' ' && i < s.length()) i++;
while (s[i] != ' ' && i < s.length()) word += s[i++];
int j = 0;
while (word[j] >= '0' && word[j] <= '9') j++;
std::string spaces = ".,;!?";
for (int i = 0; i < spaces.size(); i++)
if (word[j] == spaces[i] || word[j] == '\0') {
vek.push_back(std::stoi(word));
break;
}
}
return vek;
}
int main() {
std::string s;
std::getline(std::cin, s);
for (int i: extract_numbers(s))
std::cout << i << " ";
return 0;
}
Related Topics
Function Template with an Operator
How to Create a Thread-Safe Singleton Pattern in Windows
Advice on Mocking System Calls
What's the Best Technique for Exiting from a Constructor on an Error Condition in C++
How to Determine the Correct Size of a Qtablewidget
Zero Initialization and Static Initialization of Local Scope Static Variable
Std::Make_Tuple Doesn't Make References
Load Shared Library by Path at Runtime
When Do You Prefer Using Std::List<T> Instead of Std::Vector<T>
How to Set Application Icon in a Qt-Based Project
The Std::Transform-Like Function That Returns Transformed Container
C++ Unordered_Map Fail When Used with a Vector as Key
Const Unsigned Char * to Std::String
C++11 Lambdas: Member Variable Capture Gotcha
G++ Always Backward-Compatible with "Older" Static Libraries