Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shifting elements of a container and filling shifted place with default constructed elements

Tags:

c++

For example: c = {"aaa", "aaa"} -> c >> 1 -> c = {"", "aaa"}

I thought I can use std::shift_right but it uses std::move internally and moved from object are left unspecified state:

 std::vector<bool> bv(5, true);
 std::shift_left(begin(bv), end(bv), 4); // prints 1 1 1 1 1

After some search come up with this but wonder is there a better solution:

 std::rotate(begin(bv), begin(bv) + 4, end(bv));
 std::fill_n(begin(bv), 4, false); // 0 0 0 0 1
like image 332
Adem Budak Avatar asked Dec 06 '25 02:12

Adem Budak


1 Answers

While it is true that std::move() leaves objects in an unspecified state, you can still assign a new value to the element. So the following is perfectly fine.

constexpr size_t N = 4;
std::vector<bool> bv(5, true);
std::shift_right(bv.begin(), bv.end(), N); // prints 1 1 1 1 1 (but the first 4 elements are in an unspecified state).
std::fill_n(bv.begin(), 4, false); // 0 0 0 0 1
like image 146
Deev Avatar answered Dec 07 '25 18:12

Deev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!