перемещение элемента вниз в списке c ++ - PullRequest
1 голос
/ 21 мая 2011

Мне нужна помощь, мне нужно найти элемент в связанном списке и переместить его вниз в списке.Как я могу это сделать?

пример: 1 2 3 4

найти 2 и переключиться на следующий

выход: 1 3 2 4

ход 2на два пробела вниз 2 3 4 1

1 Ответ

1 голос
/ 21 мая 2011

Если вы используете std::list, это довольно просто.Сначала выполните поиск своего номера, чтобы получить итератор для этой позиции в списке.Например:

std::list<int> mylist;

//populate your list with the digits you want

//find the element in the list
int element = 5;
std::list<int>::iterator current = mylist.begin();
for (; current != mylist.end(); current++)
{
    if (*current == element)
        break;
}

//Now move your element two positions back (let's assume you have the elements in
//the list to-do that amount of movement, but nevertheless,
//we still check the list bounds and exit the loop if we hit the front of the list)
for (std::list<int>::iterator new_position = current, int i=0; 
     (i < 2 && new_position != mylist.begin()); 
     i++, new_position--);

mylist.insert(new_position, 1, *current);

//erase where the element used to be
mylist.erase(current);

А если вы не используете std::list, используйте std::list: -)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...