c++ - 如何使用 std:move 和 back inserter 将 std::list 中的元素 move 到末尾?

标签 c++ stl move rvalue stdlist

在我的 std::list 中,我有 10 个元素,我想将数字 1000 移到列表的后面。

https://leetcode.com/playground/gucNuPit

有没有更好的方法,使用 std::move、后插入器或任何其他 C++ 语法的 1 衬里有意识地实现这一点?

// 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;
}

最佳答案

您可以使用 std::list::splice(..) 来实现这一点

myList.splice(myList.end(), myList, std::find(myList.begin(), myList.end(), 1000));

查看 documentation

关于c++ - 如何使用 std:move 和 back inserter 将 std::list 中的元素 move 到末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71368658/

相关文章:

c++ - std::get 在给定 6 个整数的元组时失败

c++ - 将加密数据保存在内存中

c++ - 仿函数的线程与解构

windows - 将多个文件从多个文件夹 move 到一个文件夹

c++ - Kinect 相机偏航运动

c++ - 如何在不同的平台有不同的 Header?

c++ - qsort 与 std::sort 的性能?

php - Wordpress: move 媒体文件夹

c++ - Codeblocks 16.01 中警告被视为错误

visual-studio-2010 - VS2010中使用set时remove_if的问题