vlasaks
vlasaks

Reputation: 13

adding and erasing elements from container, without shrinking it

How to make a container in which you can add elements, for example add on the beginning 1 2 3, then to have a couple empty spaces, and then 4, 5, 6. So it would look like this:

add(1, 0) -> add one on position 0
add(2, 1)
add(3, 2)
add(4, 5)
add(5, 6)
print() --> 0-2: 1,2,3 4-5: 4,5
erase(2, 0) -> (length, position)
print() --> 2: 3 4-5: 4,5

purpose is to add things later in the missing positions.

tyy

Upvotes: 0

Views: 65

Answers (1)

NathanOliver
NathanOliver

Reputation: 180650

You can use a std::map/std::unordered_map for this. That would look like

std::unordered_map<int, int> data;
data[0] = 1;
data[1] = 2;
data[2] = 3;
data[5] = 4;
data[6] = 5;

//print() --> 1, 2, 3, 4, 5, 6

data.erase(data.begin(), std::next(data.begin(), 2)) // erase first 2 elements

//print() --> 3, 4, 5, 6

Upvotes: 1

Related Questions