user2017078
user2017078

Reputation:

how to move everything in an array to the left once there is an empty space in the middle?

A[5] has elements {a,b,c,d,e}

A[2] becomes empty, what is the the best way to move everything to the right so that they fill up the array partially leaving the empty spaces to the far left. I know how to do it with logic and loops, I was wondering if there are any commands that would do it for me?

Upvotes: 0

Views: 1096

Answers (1)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

A C-style array has no concept of an "empty" element. The element will always have a value. You may decide that some value denotes an empty element but that's up to you. If your "empty" placeholder value is named empty, you could do something along the lines of:

auto empty_it = std::find(std::begin(arr), std::end(arr), empty);
std::rotate(empty_it, empty_it + 1, std::end(arr));

This will move the first empty element to the back of the array.

You'd be much better off using a std::vector, std::list, or other standard library container. They provide functions for removing elements from the container without you having to care about shifting elements around. For example:

std::vector<int> v = {0, 1, 2, 3, 4, 5, 6};
v.erase(v.begin() + 3);
for (auto& x : v) {
    std::cout << x << " ";
}

This will print 0 1 2 4 5 6. The 3 has been removed from the container.

Upvotes: 1

Related Questions