如何使用 std::move 和后插入器将 std::list 中的元素移动到末尾?
在我的 std::list 中,我有 10 个元素,我想将数字 1000 移到列表的后面。
https://leetcode.com/playground/gucNuPit
有更好的方法,使用 std 的 1 行::move、back inserter 或任何其他 C++ 语法来有意识地实现此目的?
// Move the number 1000 to the end of the list
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main() {
list<int> myList({2,3,4,1000,5,6,7,8,9,10});
cout << "List before " << endl;
for(auto e : myList)
cout << e << " ";
// get iterator to the number 1000 in the list
list<int>::iterator findIter = std::find(myList.begin(), myList.end(), 1000);
int val_to_move_to_end = *findIter;
myList.erase(findIter);
myList.push_back(val_to_move_to_end);
cout << endl << endl << "List after " << endl;
for(auto e : myList)
cout << e << " ";
return 0;
}
In my std::list, i have 10 elements, and i want to move the number 1000 to the back of the list.
https://leetcode.com/playground/gucNuPit
is there a better way, a 1 liner using std::move, back inserter or any other C++ syntax to achieve this with consciously?
// Move the number 1000 to the end of the list
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main() {
list<int> myList({2,3,4,1000,5,6,7,8,9,10});
cout << "List before " << endl;
for(auto e : myList)
cout << e << " ";
// get iterator to the number 1000 in the list
list<int>::iterator findIter = std::find(myList.begin(), myList.end(), 1000);
int val_to_move_to_end = *findIter;
myList.erase(findIter);
myList.push_back(val_to_move_to_end);
cout << endl << endl << "List after " << endl;
for(auto e : myList)
cout << e << " ";
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
std::list::splice(..)
来实现此目的查看 文档
You can use the
std::list::splice(..)
to achieve thisCheck out the documentation