simon simon - 21 days ago 6
C++ Question

C++ best way to split vector into n vector

I have a

std::vector<std::string>
in this vector I
push_back
string from txt file, like this :

std::string line;
std::vector<std::string> path;
while(getline(fichier, line))
{
path.push_back(line);
}


I would like to split path
vector
into n other
vector
of 10 line for example.
So if size of my
vector
is 25, I want 2 other vector of 10 element and one
vector
of 5 element.

What is the best way to do that ?

Answer

Best is a matter of opinion, but you could do something like the following (with bunch_size being 10):

for(size_t i = 0; i < strings.size(); i += bunch_size) {
    auto last = std::min(strings.size(), i + bunch_size);
    bunches.emplace_back(strings.begin() + i, strings.begin() + last);
}

demo

If your strings are large and you want to avoid copying, you can go with the move version:

for(size_t i = 0; i < strings.size(); i += bunch_size) {
    auto last = std::min(strings.size(), i + bunch_size);
    auto index = i / bunch_size;
    auto& vec = bunches[index];
    vec.reserve(last - i);
    move(strings.begin() + i, strings.begin() + last, back_inserter(vec));
}

demo