I find it hard to do all the string manipulation and then parsing into an array of integers in c++ while we could get away with only a single line in python.
whats the easiest way to split the string of integers into an array of integers in c++ ?
I find it hard to do all the string manipulation and then parsing into an array of integers in c++ while we could get away with only a single line in python.
whats the easiest way to split the string of integers into an array of integers in c++ ?
There are many options to do this. For example using standard stream this could be achieved using:
#include <vector>
#include <string>
#include <sstream>
std::string s = "1 2 3";
std::vector<int> result;
std::istringstream iss(s);
for(int n; iss >> n; )
result.push_back(n);
The question is too broad and there are many solutions depending on the format of your string. In the case that you want to split a string using a custom delimiter and convert it to integers (or whatever) I personally use the following function (I have absolutely no idea if there are faster ways to do it):
void split_string_with_delim(std::string input, std::string delimiter, std::vector<std::int> &output){
ulong pos;
while ((pos = input.find(delimiter)) != std::string::npos) {
std::string token = input.substr(0, pos);
output.push_back(std::stoi(token));
input.erase(0, pos + delimiter.length());
}
output.push_back(std::stoi(input));
}