Reputation: 6285
Lets say I have a std::map
with
a[1] = "One";
a[2] = "Two";
a[3] = "Three";
and this map is represent strings that user added in the list control.
Now, the user decides to drag the item 1 at the bottom of the list control.
Is there an easy way to reshuffle the map so that it is:
a[1] = "Two";
a[2] = "Three";
a[3] = "One";
Or maybe I chose a wrong data structure to hold data?
P.S.: I can't use std::vector
, because it's not a sorted container and I need to process string in that order.
Upvotes: 0
Views: 70
Reputation: 124
I know your post claim's you would be unable to use a std::vector
to store the elements as it is "not a sorted container" however, as ShadowRanger pointed out in his comment, if your use of integer keys indicates that it would be more than possible to implement a similar structure to what you are doing with std::map
with std::vector
. Using the indices of the vector as your keys. That way if you wished to iterate over the vector in ascending key order, you could simply iterate over the vector in order. You could even access the elements using the int
keys you used for your map, just starting with 0 instead of 1.
As for moving the elements, you could use some code like this
template <typename Iter>
void shiftBack(Iter begin, Iter end){
for(;end > begin; --end){
*end = std::move(*begin);
}
}
template <typename Iter>
void shiftFront(Iter begin, Iter end){
for(;begin < end; ++begin){
*(begin - 1) = std::move(*begin);
}
}
template <typename Iter>
void moveElem(Iter elemPos, Iter newPos){
if(elemPos == newPos){
return;
}
auto temp = std::move(*elemPos);
if(elemPos > newPos){
shiftBack(newPos, elemPos);
} else {
shiftFront(elemPos + 1, newPos + 1);
}
*newPos = std::move(temp);
}
This code is just an example that follows the general idea for what to do, I make no promises that it will work without error.
Upvotes: 2