gpt4 book ai didi

c++ - 在列表中向下移动一个元素 C++

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:03 27 4
gpt4 key购买 nike

我需要一些帮助,我需要能够在链表中找到一个元素并将其在链表中向下移动。我该怎么做?

例子: 1 2 3 4

找到2并切换到下一个

输出:1 3 2 4

向下移动 2 两个空格2 3 4 1

最佳答案

如果您正在使用 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 :-)

关于c++ - 在列表中向下移动一个元素 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6079701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com