ADVERTISEMENT
ADVERTISEMENT

Home » C++ STL

Remove all consecutive duplicate elements from the list | C++ STL

Example of list.unique() function in C++ STL: Here, we are going to learn how to remove consecutive duplicate elements from the list?
Submitted by IncludeHelp, on October 31, 2018

Given a list with some of the elements and we have to remove consecutive duplicate elements from the list in C++ STL.

list.unique() function

In C++ STL, to remove consecutive duplicate elements, we use a library function of "list" header, that is unique(), this function removes all consecutive duplicate elements from the list (similar to other containers also). And we get the list without consecutive duplicate elements.

Example:

    Input:
    List = {10, 10, 20, 30, 30, 10, 20, 40, 40, 50}
    
    Output:
    List elements are 
    10 10 20 30 30 10 20 40 40 50 
    List after removing consecutive duplicate elements
    10 20 30 10 20 40 50

Program:

#include <iostream>
#include <list>
using namespace std;

//function to display the list 
void dispList(list<int> L)
{
	//declaring iterator to the list 
	list<int>::iterator l_iter;
	for (l_iter = L.begin(); l_iter != L.end(); l_iter++)
	cout<< *l_iter<< " ";
		cout<<endl;
}

int main()
{
	//declaring a list 
	list<int> iList = {10, 10, 20, 30, 30, 10, 20, 40, 40, 50};

	//printing list elements
	cout<<"List elements are"<<endl;
	dispList(iList);

	//remove all consecutive duplicate elements
	iList.unique();
	cout<<"List after removing consecutive duplicate elements"<<endl;
	dispList(iList);
	
	return 0;
}

Output

List elements are
10 10 20 30 30 10 20 40 40 50
List after removing consecutive duplicate elements
10 20 30 10 20 40 50
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.