honey_ramgarhia
honey_ramgarhia

Reputation: 567

How can I divide a vector in c++

Ive tried with assign fxn but it doesnt work

c.assign(v.begin(), v.begin() + (v.size() + 1) / 2)
d.assign(v.begin() + (v.size() + 1) / 2 + 1, v.end())

for eg vec = 1,2,3,4,5,6,7,8 then it produces result vec1 = 1,2,3,4 vec2 = 6,7,8

Upvotes: 1

Views: 3158

Answers (1)

Kyle Knoepfel
Kyle Knoepfel

Reputation: 1698

Yes, the output is exactly as expected. Remember, the pair of iterators that you present to assign is a half-open interval--i.e.:

c.assign(b,e);

assigns to c the values corresponding to b through e-1. But you have added 1 to the iterator in the d.assign statement.

For your code to work how you intend, you'll want:

auto const b = v.cbegin();
auto const m = b+(v.size()+1)/2;
auto const e = v.cend();

c.assign(b,m);
d.assign(m,e);

Upvotes: 1

Related Questions