C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
List list - Constructs a list container initialized with n copies of v.
List list - Constructs a list container initialized with n copies of v.
list
Header
<list>
explicit list(const A& a1 = A())
The default constructor creates an empty container.
explicit list(size_type n, const T& v = T(), const A& a1 = A())
Constructs a list container initialized with n copies of v.
list(const list& x)
This is the copy constructor for the list container. It creates a new empty list object and copies all the elements of x into the new list.
list(const_iterator first, const_iterator last, const A& a1 = A())
Constructs a new list container. It copies all the elements specified by the range [first, last) into the new list.
Sample
#include <list>
#include <iostream>
#include <functional>
int main()
{
//default constructor
std::list<int> c1 ;
//create list with 10 copies of 4
std::list<int> c2(10, 4) ;
//copy constructor
std::list<int> c3(c2) ;
int ai[] = {0, 1, 2, 3, 4, 5} ;
int i ;
std::list<int> c4 ;
//get_allocator
std::list<int>::allocator_type a1 = c4.get_allocator() ;
//push_back
for(i = 0; i < 5; i++)
c4.push_back(ai[i]) ;
//range copy constructor
std::list<int> c5(c4.begin(), c4.end()) ;
//begin, end
std::cout << "c4 (using begin, end) = " ;
std::list<int>::iterator Iter ;
for(Iter = c4.begin(); Iter != c4.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
//rbegin, rend
std::cout << "c4 (using rbegin, rend) = " ;
std::list<int>::reverse_iterator RevIter ;
for(RevIter = c4.rbegin(); RevIter != c4.rend(); RevIter++)
std::cout << *RevIter << ", " ;
std::cout << std::endl ;
//assign
c2.assign(c5.begin(), c5.end()) ;
c1.assign(10, 4) ;
//back
std::cout << "last element in c2 = " << c2.back() << std::endl ;
//front
std::cout << "first element in c2 = " << c2.front() << std::endl ;
//size
std::cout << "number of elements in c2 = " << c2.size() << std::endl ;
//max_size
std::cout << "max number of elements c2 can hold using current allocator = "
<< c2.max_size() << std::endl ;
//erase
c3.erase(c3.begin(), c3.end()) ;
//clear
c2.clear() ;
//empty
if (c2.empty() == true)
std::cout << "c2 is now empty" << std::endl ;
//resize
c2.resize(10, 30) ;
std::cout << "number of elements in c2 = " << c2.size() << std::endl ;
std::cout << "last element in c2 = " << c2.back() << std::endl ;
std::cout << "first element in c2 = " << c2.front() << std::endl ;
//push_front
c2.push_front(25) ;
std::cout << "first element in c2 = " << c2.front() << std::endl ;
//pop_back
c2.pop_back() ;
std::cout << "last element in c2 = " << c2.back() << std::endl ;
//pop_front
c2.pop_front() ;
std::cout << "first element in c2 = " << c2.front() << std::endl ;
//swap
c3.swap(c2) ;
std::cout << "number of elements in c3 = " << c3.size() << std::endl ;
std::cout << "last element in c3 = " << c3.back() << std::endl ;
std::cout << "first element in c3 = " << c3.front() << std::endl ;
//insert
c1.insert(c1.begin(), 20) ;
c3.insert(c3.begin(), 4, 10) ;
c3.insert(c3.end(), c5.begin(), c5.end()) ;
std::cout << "c1 = " ;
for(Iter = c1.begin(); Iter != c1.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
//reverse
c3.reverse() ;
std::cout << "c3, after reversing = " ;
for(Iter = c3.begin(); Iter != c3.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
//remove
c3.remove(30) ;
std::cout << "c3, after removing all occurences of 30 = " ;
for(Iter = c3.begin(); Iter != c3.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
c2.insert(c2.begin(), 4, 10) ;
//remove_if
c2.remove_if(std::bind2nd(std::not_equal_to<int>(), 10)) ;
std::cout << "c2, after removing all elements which are not equal to 10 = " ;
for(Iter = c2.begin(); Iter != c2.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
c2.insert(c2.begin(), 35) ;
//sort
c3.sort() ;
std::cout << "c3, after sorting = " ;
for(Iter = c3.begin(); Iter != c3.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
//unique
c2.unique() ;
std::cout << "c2, after removing duplicates = " ;
for(Iter = c2.begin(); Iter != c2.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
//splice
c3.splice(c3.end(), c2) ;
c3.splice(c3.end(), c4, c4.begin()) ;
c3.splice(c3.end(), c1, c1.begin(), c1.end()) ;
c3.sort() ;
c3.unique() ;
std::cout << "c3 = " ;
for(Iter = c3.begin(); Iter != c3.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
std::cout << "c2 = " ;
for(Iter = c2.begin(); Iter != c2.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
std::cout << "c1 = " ;
for(Iter = c1.begin(); Iter != c1.end(); Iter++)
std::cout << *Iter << ", " ;
std::cout << std::endl ;
return 0 ;
}
Program Output
c4 (using begin, end) = 0, 1, 2, 3, 4,
c4 (using rbegin, rend) = 4, 3, 2, 1, 0,
last element in c2 = 4
first element in c2 = 0
number of elements in c2 = 5
max number of elements c2 can hold using current allocator = 1073741823
c2 is now empty
number of elements in c2 = 10
last element in c2 = 30
first element in c2 = 30
first element in c2 = 25
last element in c2 = 30
first element in c2 = 30
number of elements in c3 = 9
last element in c3 = 30
first element in c3 = 30
c1 = 20, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
c3, after reversing = 4, 3, 2, 1, 0, 30, 30, 30, 30, 30, 30, 30, 30, 30, 10, 10,
10, 10,
c3, after removing all occurences of 30 = 4, 3, 2, 1, 0, 10, 10, 10, 10,
c2, after removing all elements which are not equal to 10 = 10, 10, 10, 10,
c3, after sorting = 0, 1, 2, 3, 4, 10, 10, 10, 10,
c2, after removing duplicates = 35, 10,
c3 = 0, 1, 2, 3, 4, 10, 20, 35,
c2 =
c1 =
A program shall contain a global function named main, which is the designated start of the program in hosted environment. main() function is the entry point of any C++ program. It is the point at which execution of program is started. When a C++ program is executed, the execution control goes directly to the main() function. Every C++ program have a main() function.
Access first element. Returns a reference to the first element in the list container. The C++ list::front function returns a reference to the first element of the list. Please note that, Unlike the list::begin function, which returns the iterator pointing to the first element, it returns the a direct reference to the same element of the list. Unlike member list::begin, which returns an iterator to this same element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior.
List are containers that allow constant time insertion and deletion anywhere in sequence. List are implemented as doubly linked lists. List allow non-contiguous memory allocation. List perform better insertion extraction and moving of element in any position in container than array, vector and deque. In List the direct access to the element is slow and list is similar to forward_list, but forward list objects are single linked lists and they can only be iterated forwards. insert() function insert elements. The container is extended by inserting new elements before the element at the specified position. This effectively increases the list size by the amount of elements inserted. Unlike other standard sequence containers, list and forward_list objects are specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence. The arguments determine how many elements are inserted and to which values they are initialized:
List is a popularly used sequence container. Container is an object that holds data of same type. List container is implemented as doubly linked-list, hence it provides bidirectional sequential access to it's data. List doesn't provide fast random access, it only supports sequential access in both directions. List allows insertion and deletion operation anywhere within a sequence in constant time. Elements of list can be scattered in different chunks of memory. Container stores necessary information to allow sequential access to it's data. Lists can shrink or expand as needed from both ends at run time. The storage requirement is fulfilled automatically by internal allocator. Zero sized lists are also valid. In that case list.begin() and list.end() points to same location. But behavior of calling front() or back() is undefined. To define the std::list, we have to import the <list> header file.
In computer programming, loops are used to repeat a block of code. For example, when you are displaying number from 1 to 100 you may want set the value of a variable to 1 and display it 100 times, increasing its value by 1 on each loop iteration. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop. A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
Clear content. Removes all elements from the list container (which are destroyed), and leaving the container with a size of 0. list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0. No parameters are passed. This function does not return any value.
Access last element. Returns a reference to the last element in the list container. list::back() is an inbuilt function in C++ STL which is declared in header file. back() is used to refer to the last element of the list container. This function returns a direct reference to the last element only. When the list is empty then the function performs an undefined behaviour. Unlike member list::end, which returns an iterator just past this element, this function returns a direct reference. Calling this function on an empty container causes undefined behavior. No parameter is required.
Get allocator. Returns a copy of the allocator object associated with the list container. list::get_allocator() is an inbuilt function in C++ STL which is declared in header file. get_allocator() returns the allocator of the list container. In simple words it returns a copy of the object of the list container. This function does not accept any parameter. Function returns the allocator.
Return size. Returns the number of elements in the list container. list::size() is an inbuilt function in C++ STL which is declared in <list> header file. size() returns the size of a particular list container. In other words it returns the number of elements which are present in a list container. This function does not accept any parameter. Function returns the number of elements in the container.
Return iterator to beginning. Returns an iterator pointing to the first element in the list container. Notice that, unlike member list::front, which returns a reference to the first element, this function returns a bidirectional iterator pointing to it. If the container is empty, the returned iterator value shall not be dereferenced. begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container. This function does not accept any parameter. Function returns an iterator to the beginning of the sequence container.
Return iterator to end. Returns an iterator referring to the past-the-end element in the list container. The past-the-end element is the theoretical element that would follow the last element in the list container. It does not point to any element, and thus shall not be dereferenced. Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator, this function is often used in combination with list::begin to specify a range including all the elements in the container. If the container is empty, this function returns the same as list::begin. This function does not accept any parameter.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program.
Transfer elements from list to list. Transfers elements from x into the container, inserting them at position. The list::splice() is a built-in function in C++ STL which is used to transfer elements from one list to another. This effectively inserts those elements into the container and removes them from x, altering the sizes of both containers. The operation does not involve the construction or destruction of any element. They are transferred, no matter whether x is an lvalue or an rvalue, or whether the value_type supports move-construction or not. The first version (1) transfers all the elements of x into the container. The second version (2) transfers only the element pointed by i from x into the container. The third version (3) transfers the range [first,last) from x into the container.
Assign new content to container. Assigns new contents to the list container, replacing its current contents, and modifying its size accordingly. The list::assign() is a built-in function in C++ STL which is used to assign values to a list. It can also be used to copy elements from one list to another. This function does not return any value.
Reverse the order of elements. Reverses the order of the elements in the list container. The list::reverse() is a built-in function in C++ STL which is used to reverse a list container. It reverses the order of elements in the list container. This function does not accept any parameter. This function does not return any value.
Iterators are just like pointers used to access the container elements. Iterators are one of the four pillars of the Standard Template Library or STL in C++. An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container. They allow you to iterate over the container, access and assign the values, and run different operators over them, to get the desired result. • Iterators are used to traverse from one element to another element, a process is known as iterating through the container. • The main advantage of an iterator is to provide a common interface for all the containers type. • Iterators make the algorithm independent of the type of the container used.
Function object class for non-equality comparison. Binary function object class whose call returns whether its two arguments compare not equal (as returned by operator operator!=). Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a function call. This function does not return any value.
Return reverse iterator to reverse end. Returns a reverse iterator pointing to the theoretical element preceding the first element in the list container (which is considered its reverse end). The C++ list::rend function returns the reverse iterator pointing to the element preceding the first element (reversed past-the-last element) of the list. A reverse iterator iterates in backward direction and increasing it results into moving to the beginning of the list container. Similarly, decreasing a reverse iterator results into moving to the end of the list container. The range between list::rbegin and list::rend contains all the elements of the container (in reverse order).
Return reverse iterator to reverse beginning. Returns a reverse iterator pointing to the last element in the container (i.e., its reverse beginning). list::rbegin() is an inbuilt function in C++ STL which is declared in header file. rbegin() is a reverse begin function. rebegin() returns a reverse iterator which is pointing to the last element of the list. Reverse iterator is an iterator which moves in reverse direction, starting from the end and will move towards the start. However back() also returns the last element but unlike the simple iterator this bidirectional iterator moves in backward direction. Reverse iterators iterate backwards: increasing them moves them towards the beginning of the container. rbegin points to the element right before the one that would be pointed to by member end.
Return maximum size. Returns the maximum number of elements that the list container can hold. list::max_size() is an inbuilt function in C++ STL which is declared in header file. max_size() returns the maximum size of the list container. In other words it returns the maximum size that a container can reach, however there is no guarantee it can allocate the elements of that size, it can still fail to allocate the storage to a specific point of a list container. This is the maximum potential size the container can reach due to known system or library implementation limitations, but the container is by no means guaranteed to be able to reach that size: it can still fail to allocate storage at any point before that size is reached. Function does not contain any parameter.
Swap content. Exchanges the content of the container by the content of x, which is another list of the same type. Sizes may differ. The C++ function std::list::swap() exchanges the contents of the first list with another. This function changes size of list if necessary. After the call to this member function, the elements in this container are those which were in x before the call, and the elements of x are those which were in this. All iterators, references and pointers remain valid for the swapped objects. Notice that a non-member function exists with the same name, swap, overloading that algorithm with an optimization that behaves like this member function. Whether the container allocators are also swapped is not defined, unless in the case the appropriate allocator trait indicates explicitly that they shall propagate.
Delete last element. Removes the last element in the list container, effectively reducing the container size by one. The list::pop_back() is a built-in function in C++ STL which is used to remove an element from the back of a list container. That is, this function deletes the last element of a list container. This function thus decreases the size of the container by 1 as it deletes an element from the end of list. This destroys the removed element. This function does not accept any parameter.
Function changes size of the list. Resizes the container so that it contains n elements. The list::resize() is a built-in function in C++ STL which is used to resize a list container. It takes a number n as parameter and resizes the list container to contain exactly n elements. If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them). If n is greater than the current container size, the content is expanded by inserting at the end as many elements as needed to reach a size of n. If val is specified, the new elements are initialized as copies of val, otherwise, they are value-initialized. Notice that this function changes the actual content of the container by inserting or erasing elements from it.
Insert element at beginning. Inserts a new element at the beginning of the list, right before its current first element. The content of val is copied (or moved) to the inserted element. The list::push_front() is a built-in function in C++ STL which is used to insert an element at the front of a list container just before the current top element. This function also increases the size of the container by 1. This effectively increases the container size by one. This function does not return any value.
Remove elements fulfilling condition. Removes from the container all the elements for which Predicate pred returns true. This calls the destructor of these objects and reduces the container size by the number of elements removed. remove_if() function is used to remove all the values from the list that correspond true to the predicate or condition given as parameter to the function. The function iterates through every member of the list container and removes all the element that return true for the predicate. The function calls pred(*i) for each element (where i is an iterator to that element). Any of the elements in the list for which this returns true, are removed from the container. This can either be a function pointer or a function object.
Erase elements. Removes from the list container either a single element (position) or a range of elements ([first,last)). The list::erase() is a built-in function in C++ STL which is used to delete elements from a list container. This function can be used to remove a single element or a range of elements from the specified list container. This effectively reduces the container size by the number of elements removed, which are destroyed. Unlike other standard sequence containers, list and forward_list objects are specifically designed to be efficient inserting and removing elements in any position, even in the middle of the sequence.
Delete first element. Removes the first element in the list container, effectively reducing its size by one. pop_front() is an inbuilt function in C++ STL which is declared in header file. pop_front() is used to pop (delete) the element from the beginning of the list container. The function deletes the first element of the list container, means the second element of the container becomes the first element and the first element from the container is removed from the container. This function decreases the size of the container by 1. This destroys the removed element. pop_front() is an inbuilt function in C++ STL which is declared in header file. pop_front() is used to pop (delete) the element from the beginning of the list container. The function deletes the first element of the list container, means the second element of the container becomes the first element and the first element from the container is removed from the container. This function decreases the size of the container by 1.
In computer programming, we use the if statement to run a block code only when a certain condition is met. An if statement can be followed by an optional else statement, which executes when the boolean expression is false. There are three forms of if...else statements in C++: • if statement, • if...else statement, • if...else if...else statement, The if statement evaluates the condition inside the parentheses ( ). If the condition evaluates to true, the code inside the body of if is executed. If the condition evaluates to false, the code inside the body of if is skipped.
Sort elements in container. Sorts the elements in the list, altering their position within the container. The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison. The sorting is performed by applying an algorithm that uses either operator< (in version (1)) or comp (in version (2)) to compare elements. This comparison shall produce a strict weak ordering of the elements (i.e., a consistent transitive comparison, without considering its reflexiveness). The resulting order of equivalent elements is stable: i.e., equivalent elements preserve the relative order they had before the call. The entire operation does not involve the construction, destruction or copy of any element object. Elements are moved within the container.
Add element at the end. Adds a new element at the end of the list container, after its current last element. The content of val is copied (or moved) to the new element. This effectively increases the container size by one. The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container. This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name. This function does not return any value.
Remove elements with specific value. Removes from the container all the elements that compare equal to val. This calls the destructor of these objects and reduces the container size by the number of elements removed. Unlike member function list::erase, which erases elements by their position (using an iterator), this function (list::remove) removes elements by their value. A similar function, list::remove_if, exists, which allows for a condition other than an equality comparison to determine whether an element is removed.
Test whether container is empty. Returns whether the list container is empty (i.e. whether its size is 0). The C++ list::empty function is used to check whether the list is empty or not. It returns true if the size of the list is zero, else returns false. This function does not modify the container in any way. To clear the content of a list container, see list::clear. No parameter is passed to the function. Function returns true if the container size is 0, false otherwise.
Return function object with second parameter bound. This function constructs an unary function object from the binary function object op by binding its second parameter to the fixed value x. The function object returned by bind2nd has its operator() defined such that it takes only one argument. This argument is used to call binary function object op with x as the fixed value for the second argument. This function template creates a binder2nd function object. The bind2nd function is a convenient way to construct a binder2nd object. Use bind2nd when you have a binary function and always want to supply the same value as the first argument to the function.
This class reverses the direction in which a bidirectional or random-access iterator iterates through a range. A copy of the original iterator (the base iterator) is kept internally and used to reflect the operations performed on the reverse_iterator: whenever the reverse_iterator is incremented, its base iterator is decreased, and vice versa. A copy of the base iterator with the current state can be obtained at any time by calling member base. Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is pointing to the last element (not past it) of the range (this would be the first element of the reversed range). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element
Remove duplicate values. The version with no parameters (1), removes all but the first element from every consecutive group of equal elements in the container. list::unique() is an inbuilt function in C++ STL which removes all duplicate consecutive elements from the list. It works only on sorted list. Notice that an element is only removed from the list container if it compares equal to the element immediately preceding it. Thus, this function is especially useful for sorted lists. The second version (2), takes as argument a specific comparison function that determine the "uniqueness" of an element. In fact, any behavior can be implemented (and not only an equality comparison), but notice that the function will call binary_pred(*i,*(i-1)) for all pairs of elements (where i is an iterator to an element, starting from the second) and remove i from the list if the predicate returns true.
In C++ code, 'Declare and define' the function test(). Within the try block check whether the value is 'greater than zero' or not. If the value greater than zero 'throw the value' and catch
In C++ language, Multilevel Inheritance The class A serves as a base class for the derived class B, which in turn serves as a 'base class' for the derived class C. The class B is known
Operators declared on the type list. Reading a list from input. Writing a list on the output. Gets a list and returns its length. Getting an element and returns its positon in the list. If