C++:Removing nth element from a std::list This program removes elements from a list based on the position or index input by the user and all the elements of the list can be removed using this if the user wants to continue. When an element is removed from the list, the entire list moves towards the left. {E,G,H,K,M} For example, if our list above has 5 elements {E,G,H,K,M} at the beginning and the user inputs 3 to remove third element %u2018H%u2019 , the new list will look like this. {E,G,K,M} The advantage of this code: 1. The complete code is template base. So it will work with all the data types including class objects. 2. Easy to specialize the template as per your requirement. Program: /* removing nth element from std:: list */ #include <iostream> using std::ostream; #include <list> using std::list; #include <iterator> #include <numeric> //Function for removing the element whose index or position is passed as a parameter template<class T> void removeElement(T& items, int& index) { std::list<typename>::iterator range_begin =items.begin(); std::advance(range_begin,index); items.erase(range_begin); std::cout << "Element removed is "<<*range_begin << '\n'; } //Function for printing all the elements of a list template<class T> void printElements(T& items) { std::list<typename>::const_iterator it; std::cout << "The list is "<<'\n'; it=items.begin(); while(it!=items.end()) { std::cout << *it<<","; it++; } std::cout << '\n'; } //Main program int main() { int n =1 ; std::list<int> my_list(5); char answer; //Generating random numbers to populate the list std::generate(my_list.begin(),my_list.end(),[](){ return rand() % 100;}); printElements(my_list); std::cout<<"Please enter what element you want to remove,1 for first,2 for second"<<'\n'; do { std::cin >> n; // read user input for element position if ((n > my_list.size())|| (n<=0)) //is user input in invalid or out of range { std::cout<<"Please enter a number > 0 and <= "<<my_list.size()<<'\n'; } else { n=n-1; // indexing starts from 0 removeElement(my_list,n); if (my_list.empty()) { std::cout <<"The list is empty."<<'\n'; break; } printElements(my_list); std::cout <<"Do you want to remove another element? Enter 'Y' or 'N':"<<'\n'; //to continue removing elements std::cin>>answer; if ((answer=='Y') || (answer=='y')) std::cout<<"Please enter what element you want to remove,1 for first,2 for second"<<'\n'; else break; } }while(!my_list.empty()); ; return 0; }
Comments