Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do i move a number in the std::list to the end using std:move and back inserter?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading