Home > Software design >  How to move an element in std::list to the end using std:move and back inserter?
How to move an element in std::list to the end using std:move and back inserter?

Time:03-07

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

CodePudding user response:

You can use the std::list::splice(..) to achieve this

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

Check out the documentation

  • Related