split a vector c++ code example

Example 1: split vector in half cpp

std::vector<int> vec = {89, 15, 51, 27, 98};
std::size_t const half_size = vec.size() / 2;
std::vector<int> half1(vec.begin(), vec.begin() + half_size);
std::vector<int> half2(vec.begin() + half_size, vec.end());

Example 2: 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);
}

Tags:

Cpp Example