i have an array of strings
how do i take the last two elements, and insert them in positions [0] and [1] of the array respectively, and the original elements two places up?
thanks.
Printable View
i have an array of strings
how do i take the last two elements, and insert them in positions [0] and [1] of the array respectively, and the original elements two places up?
thanks.
If you are talking about C arrays, you need to move all the elements up two positions, one by one (starting on the top of course).
If you are not bound to use C arrays, use a container that allows inserting and removing on both sides, e.g. a deque or a list.
I assume that you want to remove the last two elements
and move them to the beginning. That is (for an int example) :
0 1 2 3 4 5 6
change to
5 6 0 1 2 3 4
if so, you might be able to use std::rotate in <algorithm>, but it
depends on what your "array of strings" looks like.
deque looks promising
ok, currently i haveto achieve what i asked originally. Is there a more efficient way of using deque todo this?Code:playerList.push_front(playerList.back());
playerList.pop_back();
playerList.push_front(playerList.back());
playerList.pop_back();
It may be possible to write something more efficient, but that one is already efficient.
Complexity is O(1).
what would be the simplest way of seeing if a deque contains a particular element?
there an easier way then this?Code:bool inList(deque<string>list, string str)
{
for(int i = 0; i < list.size(); i++)
if(list[i] == str)
return true;
return false;
}
You can use the find algorithm:
Code:return (find(list.begin(), list.end(), str) != list.end());