Professional Documents
Culture Documents
Lists - Are Sequence Containers That Allow Constant Time Insert and Erase Operations Anywhere
Lists - Are Sequence Containers That Allow Constant Time Insert and Erase Operations Anywhere
Lists - Are Sequence Containers That Allow Constant Time Insert and Erase Operations Anywhere
Lists - are sequence containers that allow constant time insert and erase operations anywhere
within the sequence, and iteration in both directions. As compared to vector (a type of array that
is one dimensional), list has slow traversal, but once a position has been found, insertion and
deletion are quick.
Below program show how to create a List in C++.
#include <iostream>
#include <list>//List library to be included in the program
using namespace std;
int main()
{
list <int> gqlist1; //declare your list container
//Use for loop to iterate numbers from 1 to 10 and list each number to the list.
for (int i = 1; i <= 10; ++i)
{
gqlist1.push_back(i); //insert the value of i to list
}
cout << "\nList 1 (gqlist1) is : ";
showlist(gqlist1); //call the function that will print items of our list
return 0;
}
02 Handout Page 1 of 4
DATA STRUCTURES AND ALGORITHM
Output:
pop_front() – Removes the first element of the list, and reduces size of the list by 1.
Syntax: listcontainername.pop_front();
Example: gqlist1.pop_front(); //this will remove the first element of list gqlist1 which is 1.
pop_back() – Removes the last element of the list, and reduces size of the list by 1
Syntax: listcontainername.pop_back();
Example: gqlist1.pop_back(); //this will remove the last element of list gqlist1 which is 10.
02 Handout Page 2 of 4
DATA STRUCTURES AND ALGORITHM
insert() – Inserts new elements in the list before the element at a specified position.
Syntax: listcontainername.insert(iterator,valuetoinsert);
Example: list<int>::iterator x; //declare first an iterator
x=gqlist1.begin(); //set iterator to the beginning position of the list which will
be 0.
advance(x,2); //if you would like to insert after beginning position,
advance the iterator to position you would like to insert.
gqlist1.insert(x,7); // 7 will be inserted at index 2 of the list gqlist1.
02 Handout Page 3 of 4
DATA STRUCTURES AND ALGORITHM
assign() – Assigns new elements to list by replacing current elements and resizes the list.
Syntax: listcontainername.assign(numofitems, valuetoassign);
Example: gqlist.assign(3,7); //assign a new items to list. Now we have three (3) number
7 in our list.
remove() – Removes all the elements from the list, which are equal to given element.
Syntax: listcontainername.remove(valuetoremove);
Example: gqlist.remove(7); //removes all 7 in our list. The list is now empty.
References:
class template std::list. Retrieved January 10, 2020 at
http://www.cplusplus.com/reference/list/list/
List in C++ Standard Template Library (STL). Retrieved January 10, 2020 at
https://www.geeksforgeeks.org/list-cpp-stl/
02 Handout Page 4 of 4