c++ split vector by value code example

Example 1: split string on character vector C++

string s, tmp; 
stringstream ss(s);
vector<string> words;

// If there is one element (so komma) then push the whole string
if(getline(ss, tmp, ',').fail()) {
  words.push_back(s);
}
while(getline(ss, tmp, ',')){
    words.push_back(tmp);
}

Example 2: Split a number and store it in vector

#include <bits/stdc++.h>
using namespace std;
main() {
	int n = 1213456;
	vector<int> v;
	for(; n; n/=10)
  		v.push_back( n%10 );
	reverse(v.begin(), v.end());
	for (auto &i : v) cout<<i;
}

Tags:

Cpp Example