Click to See Complete Forum and Search --> : array manipulation


dave2k
November 12th, 2005, 04:20 PM
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.

treuss
November 12th, 2005, 04:45 PM
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.

Philip Nicoletti
November 12th, 2005, 06:25 PM
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.

dave2k
November 12th, 2005, 07:06 PM
deque looks promising

dave2k
November 12th, 2005, 07:24 PM
ok, currently i have playerList.push_front(playerList.back());
playerList.pop_back();
playerList.push_front(playerList.back());
playerList.pop_back();to achieve what i asked originally. Is there a more efficient way of using deque todo this?

SuperKoko
November 13th, 2005, 04:12 AM
It may be possible to write something more efficient, but that one is already efficient.
Complexity is O(1).

dave2k
November 13th, 2005, 05:56 AM
what would be the simplest way of seeing if a deque contains a particular element?

dave2k
November 13th, 2005, 06:02 AM
there an easier way then this?
bool inList(deque<string>list, string str)
{
for(int i = 0; i < list.size(); i++)
if(list[i] == str)
return true;
return false;
}

treuss
November 13th, 2005, 09:33 AM
You can use the find algorithm:
return (find(list.begin(), list.end(), str) != list.end());