C++ Programming Code Examples
C++ > Visual C++ 5.0 Standard C++ Library Code Examples
List insert - Inserts object x at the position specified by iterator it,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
List insert - Inserts object x at the position specified by iterator it,
insert
Header
<list>
iterator insert(iterator it, const T& x = T())
Inserts object x at the position specified by iterator it, into the list container. This version of the member function insert returns an iterator that points to the position where the new element was inserted into the list.
void insert(iterator it, size_type n, const T& x)
Inserts n copies of object x, starting at position specified by iterator it, into the list container.
void insert(iterator it, const_iterator first, const_iterator last)
Inserts the objects specified by the range [first, last), starting at position specified by iterator it, into the list container.
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 =
Functional Library not_equal_to in C++
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.
Syntax for not_equal_to in C++
#include <functional>
template <class T> struct not_equal_to;
T
Type of the arguments to compare by the functional call. The type shall support the operation (operator!=).
This function does not return any value.
Objects of this class can be used on standard algorithms such as mismatch, search or unique.
Member types
first_argument_type - T - Type of the first argument in member operator()
second_argument_type - T - Type of the second argument in member operator()
result_type - bool - Type returned by member operator()
Member functions
bool operator() (const T& x, const T& y)
Member function returning whether the arguments compare not equal (x!=y).
Exceptions - It doesn't throw any exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* The std::not_equal_to is a functional object class for non-equality comparison and binary function object class. It returns a boolean value depending upon the condition whether the two arguments are not equal or not. */
/* Function object class for non-equality comparison by not_equal_to function code example */
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
using namespace std;
// Driver Code
int main()
{
// Initialise vectors
vector<int> v1 = { 50, 55, 60,
65, 70 };
vector<int> v2 = { 50, 55, 85,
65, 70 };
// Declaring pointer of pairs
pair<vector<int>::iterator,
vector<int>::iterator>
pairs1;
// Use mismatch() function to
// search first match between
// v1 and v2
pairs1 = mismatch(v1.begin(), v1.end(),
v2.begin(),
not_equal_to<int>());
// Print the match pair
cout << "The 1st match element"
<< " of 1st container : ";
cout << *pairs1.first << endl;
cout << "The 1st match element "
<< "of 2nd container : ";
cout << *pairs1.second << endl;
return 0;
}
List Library pop_front() Function in C++
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.
Syntax for List pop_front() Function in C++
#include <list>
void pop_front();
Complexity
Constant
Iterator validity
Iterators, pointers and references referring to the element removed by the function are invalidated. All other iterators, pointers and reference keep their validity.
Data races
The container is modified. The first element is modified. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/* The list::pop_front() is a built-in function in C++ STL which is used to remove an element from the front of a list container. This function thus decreases the size of the container by 1 as it deletes the element from the front of a list. */
/* remove the first element from the list and therefore, reducing the size of the list by one with C++ List pop_front() function code example. */
#include <bits/stdc++.h>
using namespace std;
int main(){
//create a list
list<int> myList;
//inserting elements to the list
myList.push_back(1);
myList.push_back(2);
myList.push_back(3);
myList.push_back(4);
//List before applying pop_front() function
cout<<"List contains : ";
for(auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
//removing first element using pop_front()
myList.pop_front();
// List after removing element from front
cout<<"\nList after removing an element from front: ";
for (auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
return 0;
}
List Library rend() Function in C++
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).
Syntax for List rend() Function in C++
#include <list>
reverse_iterator rend() nothrow;
const_reverse_iterator rend() const nothrow;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* list::rend() is an built-in function in C++ STL which is declared in header file. rend() is a reverse end function. rend() returns a reverse iterator which is pointing to the position before the first element of the list container associated. 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. */
/* Return reverse iterator to reverse end by list rend() function code example */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<string> MyList{"Alpha","Coding","Skills"};
list<string>::reverse_iterator rit;
rit = MyList.rend();
rit--;
cout<<*rit<<" ";
rit--;
cout<<*rit<<" ";
rit--;
cout<<*rit<<" ";
return 0;
}
List Library reverse() Function in C++
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.
Syntax for List reverse() Function in C++
#include <list>
void reverse() noexcept;
Complexity
Linear in list size
Iterator validity
No changes
Data races
The container is modified. No contained elements are accessed: concurrently accessing or modifying them is safe, although iterating through the container is not.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* list::reverse() is an inbuilt function in C++ STL which is declared in header file. reverse() is used to reverse the list container, means the last element of the list becomes the first element of the list. */
/* reverse the order of elements of the list container by list::reverse function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50};
list<int>::iterator it;
cout<<"MyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
//Reverse the order of all elements of the list
MyList.reverse();
cout<<"\nMyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
return 0;
}
List Library swap() Function in C++
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.
Syntax for List swap() Function in C++
#include <list>
void swap (list& x);
x
Another list container of the same type as this (i.e., with the same template parameters, T and Alloc) whose content is swapped with that of this container.
Function does not return any value.
Complexity
Constant
Iterator validity
All iterators, pointers and references referring to elements in both containers remain valid, but now are referring to elements in the other container, and iterate in it.
Note that the end iterators do not refer to elements and may be invalidated.
Data races
Both the container and x are modified. No contained elements are accessed by the call (although see iterator validity above).
Exception safety
If the allocators in both containers compare equal, or if their allocator traits indicate that the allocators shall propagate, the function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* C++ List swap() function exchange the contents of the list with another list of same type but the sizes can be differ. */
/* swap the contents of one list with another list of same type and size by List swap() function code example. */
#include <iostream>
#include<list>
using namespace std;
int main()
{
std::list<char> li={'+','-','*','@'};
list<char> li1={'j','a','v','a'};
std::cout << "Initially,content of list li is :";
for(list<char> :: iterator itr=li.begin();itr!=li.end();++itr)
cout<<*itr;
std::cout << '\n'<<"Initially,content of list li1 is :";
for(list<char> :: iterator itr=li1.begin();itr!=li1.end();++itr)
cout<<*itr;
li.swap(li1);
cout<<'\n';
cout<<"After swapping, content of list li is :";
for(list<char> :: iterator itr=li.begin();itr!=li.end();++itr)
cout<<*itr;
cout<<'\n';
cout<<"After swapping, content of list li1 is :";
for(list<char> :: iterator itr=li1.begin();itr!=li1.end();++itr)
cout<<*itr;
return 0;
}
List Library splice() Function in C++
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.
Syntax for List splice() Function in C++
#include <list>
//entire list (1)
void splice (const_iterator position, list& x);
void splice (const_iterator position, list&& x);
//single element (2)
void splice (const_iterator position, list& x, const_iterator i);
void splice (const_iterator position, list&& x, const_iterator i);
//element range (3)
void splice (const_iterator position, list& x,
const_iterator first, const_iterator last);
void splice (const_iterator position, list&& x,
const_iterator first, const_iterator last);
position
Position within the container where the elements of x are inserted. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
x
A list object of the same type (i.e., with the same template parameters, T and Alloc). This parameter may be *this if position points to an element not actually being spliced (for the first version, this is never the case, but for the other versions this is possible).
i
Iterator to an element in x. Only this single element is transferred. iterator is a member type, defined as a bidirectional iterator type. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
first,last
Iterators specifying a range of elements in x. Transfers the elements in the range [first,last) to position. Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
This function does not return any value.
Complexity
Constant for (1) and (2). Up to linear in the number of elements transferred for (3).
Iterator validity
No changes on the iterators, pointers and references related to the container before the call. The iterators, pointers and references that referred to transferred elements keep referring to those same elements, but iterators now iterate into the container the elements have been transferred to.
Data races
Both the container and x are modified. Concurrently accessing or modifying their elements is safe, although iterating x or ranges that include position is not.
Exception safety
If the allocators in both containers do not compare equal, if any of the iterators or ranges specified is not valid, or if x is *this in (1), or if position is in the range [first,last) in (3), it causes undefined behavior. Otherwise, the function never throws exceptions (no-throw guarantee).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* The C++ function std::list::splice() transfers the elements in the range of first to last from x to *this by using move semantics. The elements are inserted before the element pointed to by position. */
/* Transfer elements from list to list by list splice() function code example */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50, 30, 30, 40};
list<int>::iterator it;
cout<<"MyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
//Remove all occurrences of 30 from the list
cout<<"\n\nRemove all occurrences of 30 from the MyList.\n";
MyList.splice(30);
cout<<"Now, MyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
return 0;
}
List Library begin() Function in C++
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.
Syntax for List begin() Function in C++
#include <list>
iterator begin() noexcept;
const_iterator begin() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* returns a random access iterator which points to the first element of the list by std::list::begin() function code example */
// CPP program to illustrate implementation of end() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
// declaration of list container
list<int> mylist{ 1, 2, 3, 4, 5 };
// using end() to print list
for (auto it = mylist.begin(); it !=
mylist.end(); ++it)
cout << ' ' << *it;
return 0;
}
#include Directive in C++
#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.
Syntax for #include Directive in C++
#include "user-defined_file"
#include <header_file>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/* using #include directive in C language */
#include <stdio.h>
int main()
{
/*
* C standard library printf function
* defined in the stdio.h header file
*/
printf("I love you Clementine");
printf("I love you so much");
printf("HappyCodings");
return 0;
}
List Library remove_if() Function in C++
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.
Syntax for List remove_if() Function in C++
#include <list>
template <class Predicate>
void remove_if (Predicate pred);
pred
Unary predicate that, taking a value of the same type as those contained in the forward_list object, returns true for those values to be removed from the container, and false for those remaining.
This can either be a function pointer or a function object.
This function does not return any value.
Complexity
Linear in list size (applications of pred).
Iterator validity
Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and reference keep their validity.
Data races
The container is modified. The elements removed are modified. Concurrently accessing or modifying other elements is safe, although iterating through the container is not.
Exception safety
If pred is guaranteed to not throw, the function never throws exceptions (no-throw guarantee).
Otherwise, if an exception is thrown, the container is left in a valid state (basic guarantee).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* The C++ function std::list::remove_if() removes elements from the list that fulfills the condition. It removes all elements for which predicate returns true. */
/* remove the values which returns true to predicate or return true for condition passed as parameter by list remove_if() function code example. */
#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, 20, 11, 22, 21, -10, -20, 13, 55, 44};
//printing list elements
cout<<"List elements are"<<endl;
dispList(iList);
//remove only negative numbers
iList.remove_if([](int n) {return (n<0); });
cout<<"List elements after removing Negative elements"<<endl;
dispList(iList);
//remove the elements which are divisible by 11
iList.remove_if([](int n) {return (n%11==0); });
cout<<"List elements after removing divisble by 11"<<endl;
dispList(iList);
//remove the elements which are greater than 20
iList.remove_if([](int n) {return (n>20); });
cout<<"List elements after removing greater than 20"<<endl;
dispList(iList);
return 0;
}
List Library end() Function in C++
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.
Syntax for List end() Function in C++
#include <list>
iterator end() noexcept;
const_iterator end() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* returns a random access iterator which points to the last element of the list by std::list::end() function code example */
// CPP program to illustrate the list::end() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating a list
list<int> demoList;
// Add elements to the List
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
// using end() to get iterator
// to past the last element
list<int>::iterator it = demoList.end();
// This will not print the last element
cout << "Returned iterator points to : " << *it << endl;
// Using end() with begin() as a range to
// print all of the list elements
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
return 0;
}
List Library rbegin() Function in C++
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.
Notice that unlike member list::back, which returns a reference to this same element, this function returns a reverse bidirectional iterator.
Syntax for List rbegin() Function in C++
#include <list>
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). No contained elements are accessed by the call, but the iterator returned can be used to access or modify elements. Concurrently accessing or modifying different elements is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. The copy construction or assignment of the returned iterator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* The C++ list::rbegin function returns the reverse iterator pointing to 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. Please note that, Unlike the list::back function, which returns a direct reference to the last element, it returns the reverse iterator pointing to the same element of the list. */
/* Return reverse iterator to reverse beginning by list rbegin() function code example */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<string> MyList{"Alpha","Coding","Skills"};
list<string>::reverse_iterator rit;
rit = MyList.rbegin();
cout<<*rit<<" ";
rit++;
cout<<*rit<<" ";
rit++;
cout<<*rit<<" ";
return 0;
}
List Library insert() Function in C++
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:
Syntax for List insert() Function in C++
#include <list>
//single element (1)
iterator insert (const_iterator position, const value_type& val);
//fill (2)
iterator insert (const_iterator position, size_type n, const value_type& val);
//range (3)
template <class InputIterator>
iterator insert (const_iterator position, InputIterator first, InputIterator last);
//move (4)
iterator insert (const_iterator position, value_type&& val);
//initializer list (5)
iterator insert (const_iterator position, initializer_list<value_type> il);
position
Position in the container where the new elements are inserted. iterator is a member type, defined as a bidirectional iterator type that points to elements.
val
Value to be copied (or moved) to the inserted elements. Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
n
Number of elements to insert. Each element is initialized to a copy of val. Member type size_type is an unsigned integral type.
first, last
Iterators specifying a range of elements. Copies of the elements in the range [first,last) are inserted at position (in the same order).
Notice that the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
The function template argument InputIterator shall be an input iterator type that points to elements of a type from which value_type objects can be constructed.
il
An initializer_list object. Copies of these elements are inserted at position (in the same order).
These objects are automatically constructed from initializer list declarators.
Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
Function returns an iterator that points to the first of the newly inserted elements.
Member type iterator is a bidirectional iterator type that points to elements.
The storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
• The function is use to insert the element at specified position.
• The function is also use to insert the n No. of element in list.
• It is also use insert the elements in the range at the specified.
Complexity
Linear in the number of elements inserted (copy/move construction).
Iterator validity
No changes.
Data races
The container is modified. No contained elements are accessed. Concurrently accessing or modifying different elements is safe, although iterating ranges that include position is not.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
If allocator_traits::construct is not supported with the appropriate arguments for the element constructions, or if an invalid position or range is specified, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/* insert the elements at any position of list by list::insert() function code example */
// C++ code to demonstrate the working of insert() function
#include <iostream>
#include <list> // for list operations
using namespace std;
int main()
{
// declaring list
list<int> list1;
// using assign() to insert multiple numbers
// creates 3 occurrences of "2"
list1.assign(3, 2);
// initializing list iterator to beginning
list<int>::iterator it = list1.begin();
// iterator to point to 3rd position
advance(it, 2);
// using insert to insert 1 element at the 3rd position
// inserts 5 at 3rd position
list1.insert(it, 5);
// Printing the new list
cout << "The list after inserting"
<< " 1 element using insert() is : ";
for (list<int>::iterator i = list1.begin();
i != list1.end();
i++)
cout << *i << " ";
cout << endl;
// using insert to insert
// 2 element at the 4th position
// inserts 2 occurrences
// of 7 at 4th position
list1.insert(it, 2, 7);
// Printing the new list
cout << "The list after inserting"
<< " multiple elements "
<< "using insert() is : ";
for (list<int>::iterator i = list1.begin();
i != list1.end();
i++)
cout << *i << " ";
cout << endl;
}
List Library size() Function in C++
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.
Syntax for List size() Function in C++
#include <list>
size_type size() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* list::size() function in C++ is used to find the number of elements present in a list container. That is, it is used to find the size of the list container. */
/* find the number of elements present in the list by size() function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50};
cout<<"List size is: "<<MyList.size()<<"\n";
cout<<"Three elements are added in the List.\n";
MyList.push_back(60);
MyList.push_back(70);
MyList.push_back(80);
cout<<"Now, List size is: "<<MyList.size()<<"\n";
return 0;
}
List Library empty() Function in C++
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.
Syntax for List empty() Function in C++
#include <list>
bool empty() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* list::empty() is an inbuilt function in C++ STL which is declared in header file. list::empty() checks whether the given list container is empty(size is 0) or not, and returns true value if the list is empty and false if the list is not empty. */
/* check whether the list is empty or not by C++ List empty() function code example. */
#include <iostream>
#include <list>
using namespace std;
int main()
{
//declare and initialize lists
list<int> list1 {10, 20, 30, 40, 50};
list<int> list2;
//check list1 is empty or not
if(list1.empty())
cout<<"list1 is an empty list\n";
else
cout<<"list1 is not an empty list\n";
//check list2 is empty or not
if(list2.empty())
cout<<"list2 is an empty list\n";
else
cout<<"list2 is not an empty list\n";
return 0;
}
List Library erase() Function in C++
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.
Syntax for List erase() Function in C++
#include <list>
iterator erase (const_iterator position);
iterator erase (const_iterator first, const_iterator last);
position
Iterator pointing to a single element to be removed from the list. Member types iterator and const_iterator are bidirectional iterator types that point to elements.
first, last
Iterators specifying a range within the list to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
Member types iterator and const_iterator are bidirectional iterator types that point to elements.
Function returns an iterator pointing to the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.
Member type iterator is a bidirectional iterator type that points to elements.
Complexity
Linear in the number of elements erased (destructions).
Iterator validity
Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity.
Data races
The container is modified. The elements removed are modified.
Concurrently accessing or modifying other elements is safe, although iterating ranges that include the removed elements is not.
Exception safety
If position (or the range) is valid, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* list::erase() is an inbuilt function in C++ STL which is declared in header file. erase() is used to remove elements from the list container. We can erase a single element or range of elements from the list container. It reduces the size of the list container by the number of elements to be removed/erased */
/* remove single element from the the list and decreases it's size by one by list::erase() function code example. */
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating a list
list<int> demoList;
// Add elements to the List
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
demoList.push_back(50);
// Printing elements of list before deleting
// any element
cout << "List before deleting any element: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
// Creating iterators of the list
list<int>::iterator itr1, itr2;
itr1 = demoList.begin();
itr2 = demoList.begin();
// Incrementing itr2 by 3 positions
advance(itr2, 3);
// deleting range of elements from index [0, 3)
demoList.erase(itr1, itr2);
// Printing elements of list after deleting
// range of elements from [0, 3)
cout << "\nList after deleting first three elements: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
return 0;
}
List Library pop_back() Function in C++
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.
Syntax for List pop_back() Function in C++
#include <list>
void pop_back();
Complexity
Constant
Iterator validity
Iterators, pointers and references referring to element removed by the function are invalidated. All other iterators, pointers and reference keep their validity.
Data races
The container is modified. The last element is modified. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* list::pop_back() is an inbuilt function in C++ STL which is declared in <list> header file. pop_back() is used to remove/pop the element from the back or the last of the list container. When we use pop_back then it remove/pops the last element and the element before the last element becomes the last element and the size of the list container is reduced by 1.*/
/* remove the last element from list and reduces size of the list by one by list pop_back() function code example. */
#include <bits/stdc++.h>
using namespace std;
int main(){
//create a list
list<int> myList;
//inserting elements to a list
myList.push_back(4);
myList.push_back(9);
myList.push_back(1);
myList.push_back(3);
//list before poping out the elements
cout<<"list elements before deletion : ";
for (auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
//removing elements from the end of a list using pop_back()
myList.pop_back();
// List after removing element from end
cout << "\nList after deleting element from the end: ";
for (auto i = myList.begin(); i != myList.end(); i++)
cout << *i << " ";
return 0;
}
Iterators in C++ Language
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.
Syntax for Iterators in C++
<ContainerType> :: iterator;
<ContainerType> :: const_iterator;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* Iterators in C++ language */
// C++ code to demonstrate the working of next() and prev()
#include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1, 2, 3, 4, 5 };
// Declaring iterators to a vector
vector<int>::iterator ptr = ar.begin();
vector<int>::iterator ftr = ar.end();
// Using next() to return new iterator
// points to 4
auto it = next(ptr, 3);
// Using prev() to return new iterator
// points to 3
auto it1 = prev(ftr, 3);
// Displaying iterator position
cout << "The position of new iterator using next() is : ";
cout << *it << " ";
cout << endl;
// Displaying iterator position
cout << "The position of new iterator using prev() is : ";
cout << *it1 << " ";
cout << endl;
return 0;
}
List Library unique() Function in C++
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.
The elements removed are destroyed.
Syntax for List unique() Function in C++
#include <list>
//(1)
void unique();
//(2)
template <class BinaryPredicate>
void unique (BinaryPredicate binary_pred);
binary_pred
Binary predicate that, taking two values of the same type than those contained in the list, returns true to remove the element passed as first argument from the container, and false otherwise.
This shall be a function pointer or a function object.
This function does not return any value.
Complexity
Linear in container size minus one.
Iterator validity
Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity.
Data races
The container is modified. The elements removed are modified. Concurrently accessing or modifying other elements is safe, although iterating through the container is not.
Exception safety
If binary_pred or the comparison of elements is guaranteed to not throw, the function never throws exceptions (no-throw guarantee).
Otherwise, if an exception is thrown, the container is left in a valid state (basic guarantee).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/* The C++ function std::list::unique() Removes all consecutive duplicate elements from the list. It uses binary predicate for comparison. */
/* remove all the duplicate elements present consecutively from the list by List unique() function code example. */
#include <bits/stdc++.h>
using namespace std;
// Function for binary_predicate
bool compare(double a, double b)
{
return ((int)a == (int)b);
}
// Driver code
int main()
{
list<double> list = { 2.55, 3.15, 4.16, 4.16,
4.77, 12.65, 12.65, 13.59 };
cout << "List is: ";
//sort the list
list.sort();
// unique operation on list with no parameters
list.unique();
// starts from the first element
// of the list to the last
for (auto it = list.begin(); it != list.end(); ++it)
cout << *it << " ";
// unique operation on list with parameter
list.unique(compare);
cout << "\nList is: ";
// starts from the first element
// of the list to the last
for (auto it = list.begin(); it != list.end(); ++it)
cout << *it << " ";
return 0;
}
List Library front() Function in C++
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.
Syntax for List front() Function in C++
#include <list>
reference front();
const_reference front() const;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The first element is potentially accessed or modified by the caller. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. */
/* return the first element of the list by front() function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50};
cout<<"The first element of MyList is: ";
cout<<MyList.front();
cout<<"\n\nAdd 100 to the first element of the MyList.\n";
MyList.front() = MyList.front() + 100;
cout<<"Now, The first element of MyList is: ";
cout<<MyList.front();
return 0;
}
List Library back() Function in C++
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.
Syntax for List back() Function in C++
#include <list>
reference back();
const_reference back() const;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed (neither the const nor the non-const versions modify the container). The last element is potentially accessed or modified by the caller. Concurrently accessing or modifying other elements is safe.
Exception safety
If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* The list::back() function in C++ STL returns a direct reference to the last element in the list container. This function is different from the list::end() function as the end() function returns only the iterator to the last element. */
/* Return the last element of the list by List back() function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50};
cout<<"The last element of MyList is: ";
cout<<MyList.back();
cout<<"\n\nAdd 100 to the last element of the MyList.\n";
MyList.back() = MyList.back() + 100;
cout<<"Now, The last element of MyList is: ";
cout<<MyList.back();
return 0;
}
List in C++ Language
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.
Definition Syntax for Lists in C++
template < class Type, class Alloc =allocator<T> > class list;
T
Defines the type of element contained. You can substitute T by any data type, even user-defined types.
Alloc
Defines the type of the allocator object. This uses the allocator class template by default. It's value-dependent and uses a simple memory allocation model.
• List is a contiguous container while vector is a non-contiguous container i.e list stores the elements on a contiguous memory and vector stores on a non-contiguous memory.
• Insertion and deletion in the middle of the vector is very costly as it takes lot of time in shifting all the elements. Linklist overcome this problem and it is implemented using list container.
• List supports a bidirectional and provides an efficient way for insertion and deletion operations.
• Traversal is slow in list as list elements are accessed sequentially while vector supports a random access.
Following member types can be used as parameters or return type by member functions:
• value_type T (First parameter of the template)
• allocator_type Alloc (Second parameter of the template)
• reference value_type&
• const_reference const value_type&
• pointer value_type*
• const_pointer const value_type*
• iterator a random access iterator to value_type
• const_iterator a random access iterator to const value_type
• reverse_iterator std::reverse_iterator <iterator>
• const_reverse_iterator std::reverse_iterator <const_iterator>
• size_type size_t
• difference_type ptrdiff_t
C++ List Member Functions
• insert(): It inserts the new element before the position pointed by the iterator.
• push_back(): It adds a new element at the end of the vector.
• push_front(): It adds a new element to the front.
• pop_back(): It deletes the last element.
• pop_front(): It deletes the first element.
• empty(): It checks whether the list is empty or not.
• size(): It finds the number of elements present in the list.
• max_size(): It finds the maximum size of the list.
• front(): It returns the first element of the list.
• back(): It returns the last element of the list.
• swap(): It swaps two list when the type of both the list are same.
• reverse(): It reverses the elements of the list.
• sort(): It sorts the elements of the list in an increasing order.
• merge(): It merges the two sorted list.
• splice(): It inserts a new list into the invoking list.
• unique(): It removes all the duplicate elements from the list.
• resize(): It changes the size of the list container.
• assign(): It assigns a new element to the list container.
• emplace(): It inserts a new element at a specified position.
• emplace_back(): It inserts a new element at the end of the vector.
• emplace_front(): It inserts a new element at the beginning of the list.
Non-member overloaded functions
operator== Tests whether two lists are equal or not.
2 operator!= Tests whether two lists are equal or not.
3 operator< Tests whether first list is less than other or not.
4 operator<= Tests whether first list is less than or equal to other or not.
5 operator> Tests whether first list is greater than other or not.
6 operator>= Tests whether first list is greater than or equal to other or not.
7 swap Exchanges the contents of two list.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* using lists in C++ language simple code example */
#include <iostream>
#include <list>
using namespace std;
int main(void) {
list<int> l;
list<int> l1 = { 10, 20, 30 };
list<int> l2(l1.begin(), l1.end());
list<int> l3(move(l1));
cout << "Size of list l: " << l.size() << endl;
cout << "List l2 contents: " << endl;
for (auto it = l2.begin(); it != l2.end(); ++it)
cout << *it << endl;
cout << "List l3 contents: " << endl;
for (auto it = l3.begin(); it != l3.end(); ++it)
cout << *it << endl;
return 0;
}
For Loop Statement in C++
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.
Syntax of For Loop Statement in C++
for (initialization; condition; update) {
// body of-loop
}
initialization
initializes variables and is executed only once.
condition
if true, the body of for loop is executed, if false, the for loop is terminated.
update
updates the value of initialized variables and again checks the condition.
A new range-based for loop was introduced to work with collections such as arrays and vectors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* For Loop Statement in C++ Language */
// C++ program to find the sum of first n natural numbers
// positive integers such as 1,2,3,...n are known as natural numbers
#include <iostream>
using namespace std;
int main() {
int num, sum;
sum = 0;
cout << "Enter a positive integer: ";
cin >> num;
for (int i = 1; i <= num; ++i) {
sum += i;
}
cout << "Sum = " << sum << endl;
return 0;
}
List Library resize() Function in C++
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.
Syntax for List resize() Function in C++
#include <list>
void resize (size_type n);
void resize (size_type n, const value_type& val);
n
New container size, expressed in number of elements. Member type size_type is an unsigned integral type.
val
Object whose content is copied to the added elements in case that n is greater than the current container size. If not specified, the default constructor is used instead. Member type value_type is the type of the elements in the container, defined in list as an alias of the first template parameter (T).
This function does not return any value.
In case of growth, the storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
val - Object whose content is copied to the added elements in case that n is greater than the current container size. If not specified, the default constructor is used instead. Member type value_type is the type of the elements in the container, defined in list as an alias of the first template parameter (T).
Complexity
If the container grows, linear in the number number of elements inserted (constructor). If the container shrinks, linear in the number of elements erased (destructions), plus up to linear in the size (iterator advance).
Iterator validity
Iterators, pointers and references referring to elements removed by the function are invalidated. All other iterators, pointers and references keep their validity.
Data races
The container is modified. Removed elements are modified. Concurrently accessing or modifying other elements is safe.
Exception safety
If the operation decreases the size of the container, the function never throws exceptions (no-throw guarantee). Otherwise, if an exception is thrown, the container is left with a valid state (basic guarantee): Constructing elements or allocating storage may throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* The C++ function std::list::resize() changes the size of list. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of list. */
/* Change size of the list by std::list::resize function code example */
#include <iostream>
#include<list>
using namespace std;
int main()
{
list<int> li={1,2,3,4,5};
list<int>::iterator itr;
std::cout << "Content of list li :" << std::endl;
for(itr=li.begin();itr!=li.end();++itr)
cout<<*itr<<",";
li.resize(3);
cout<<'\n';
std::cout << "After resizing,Content of list li :" << std::endl;
for(itr=li.begin();itr!=li.end();++itr)
cout<<*itr<<",";
return 0;
}
If Else Statement in C++
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,
Syntax for If Statement in C++
if (condition) {
// body of if statement
}
Syntax for If...Else Statement
if (condition) {
// block of code if condition is true
}
else {
// block of code if condition is false
}
Syntax for If...Else...Else If Statement in C++
if (condition1) {
// code block 1
}
else if (condition2){
// code block 2
}
else {
// code block 3
}
Syntax for If Else If Ladder in C++
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* If Else Statement in C++ Language */
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
// check the boolean condition
if( a < 20 ) {
// if condition is true then print the following
cout << "a is less than 20;" << endl;
} else {
// if condition is false then print the following
cout << "a is not less than 20;" << endl;
}
cout << "value of a is : " << a << endl;
return 0;
}
List Library push_back() Function in C++
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.
Syntax for List push_back() Function in C++
#include <list>
void push_back (const value_type& val);
void push_back (value_type&& val);
val
Value to be copied (or moved) to the new element. Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
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.
The storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Complexity
Constant
Iterator validity
No changes
Data races
The container is modified.
No existing contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
If allocator_traits::construct is not supported with val as argument, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/* list::push_back() function is used to push elements into a list from the back. The new value is inserted into the list at the end, after the current last element and the container size is increased by 1.*/
// CPP program code example to illustrate application Of push_back() function
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> mylist{};
mylist.push_back(7);
mylist.push_back(89);
mylist.push_back(45);
mylist.push_back(6);
mylist.push_back(24);
mylist.push_back(58);
mylist.push_back(43);
// list becomes 7, 89, 45, 6, 24, 58, 43
// Sorting function
mylist.sort();
for (auto it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
}
List Library sort() Function in C++
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.
Syntax for List sort() Function in C++
#include <list>
//(1)
void sort();
//(2)
template <class Compare>
void sort (Compare comp);
comp
Binary predicate that, taking two values of the same type of those contained in the list, returns true if the first argument goes before the second argument in the strict weak ordering it defines, and false otherwise. This shall be a function pointer or a function object.
This function does not return any value.
Complexity
Approximately NlogN where N is the container size.
Iterator validity
No changes
Data races
The container is modified. All contained elements are accessed (but not modified). Concurrently iterating through the container is not safe.
Exception safety
Basic guarantee: if an exception is thrown, the container is in a valid state. It throws if the comparison or the moving operation of any element throws.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/* C++ List sort() function arranges the elements of a given list in an increasing order. It does not involve in any construction and destruction of elements. Elements are only moved within the container. */
/* sort the elements of the list container list::sort function code example. */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{33, 7, 45, -12, 25, 75};
list<int>::iterator it;
cout<<"MyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
//sort elements of the list
MyList.sort();
cout<<"\nMyList contains: ";
for(it = MyList.begin(); it != MyList.end(); it++)
cout<<*it<<" ";
return 0;
}
List Library get_allocator() Function in C++
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.
Syntax for List get_allocator() Function in C++
#include <list>
allocator_type get_allocator() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions. Copying any instantiation of the default allocator is also guaranteed to never throw.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* The C++ function std::list::get_allocator() returns an allocator associated with list. */
/* Get allocator list get_allocator() function code example */
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
// Creating a container of type list
list<int> mylist;
// creating a pointer of type int
int* array;
// creating array using mylist get_allocator
array = mylist.get_allocator().allocate(3);
// inserting some data into the created array
for (int i = 0; i < 3; i++)
array[i] = i;
// printing details of the created array
for (int i = 0; i < 3; i++)
cout << array[i] << " ";
}
main() Function in C++
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.
Syntax for main() Function in C++
void main()
{
............
............
}
void
void is a keyword in C++ language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
main
main is a name of function which is predefined function in C++ library.
In place of void we can also use int return type of main() function, at that time main() return integer type value.
1) It cannot be used anywhere in the program
a) in particular, it cannot be called recursively
b) its address cannot be taken
2) It cannot be predefined and cannot be overloaded: effectively, the name main in the global namespace is reserved for functions (although it can be used to name classes, namespaces, enumerations, and any entity in a non-global namespace, except that a function called "main" cannot be declared with C language linkage in any namespace).
3) It cannot be defined as deleted or (since C++11) declared with C language linkage, constexpr (since C++11), consteval (since C++20), inline, or static.
4) The body of the main function does not need to contain the return statement: if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;.
5) Execution of the return (or the implicit return upon reaching the end of main) is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program).
6) (since C++14) The return type of the main function cannot be deduced (auto main() {... is not allowed).
7) (since C++20) The main function cannot be a coroutine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* simple code example by main() function in C++ */
#include <iostream>
using namespace std;
int main() {
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
return 0;
}
List Library remove() Function in C++
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.
Syntax for List remove() Function in C++
#include <list>
void remove (const value_type& val);
val
Value of the elements to be removed.
Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
This function does not return any value.
Complexity
Linear in container size (comparisons).
Iterator validity
Iterators, pointers and references referring to elements removed by the function are invalidated.
All other iterators, pointers and reference keep their validity.
Data races
The container is modified. The elements removed are modified. Concurrently accessing or modifying other elements is safe, although iterating through the container is not.
Exception safety
If the equality comparison between elements is guaranteed to not throw, the function never throws exceptions (no-throw guarantee).
Otherwise, if an exception is thrown, the container is left in a valid state (basic guarantee).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* The list::remove() is a built-in function in C++ STL which is used to remove elements from a list container. It removes elements comparing to a value. It takes a value as the parameter and removes all the elements from the list container whose value is equal to the value passed in the parameter of the function. */
// Remove elements with specific value by list::remove() function code example
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating a list
list<int> demoList;
// Add elements to the List
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
// List before removing elements
cout << "List before removing elements: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
// delete all elements with value 20
demoList.remove(20);
// List after removing elements
cout << "\nList after removing elements: ";
for (auto itr = demoList.begin();
itr != demoList.end(); itr++) {
cout << *itr << " ";
}
return 0;
}
bind2nd() Function in C++
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.
Syntax for bind2nd() Function in C++
template <class Operation, class T>
binder2nd<Operation> bind2nd (const Operation& op, const T& x);
op
Binary function object derived from binary_function.
x
Fixed value for the second parameter of op.
Function returns an unary function object equivalent to op but with the second parameter always set to x.
binder2nd is a type derived from unary_function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* return function object with second parameter bound by bind2nd() function code example */
#include <algorithm>
#include <functional>
#include <iostream>
#include <array>
class multip : public std::binary_function<int, int, void>
{
public:
void operator()(int val, int to) const {
std::cout << (val *= to) << std::endl;
}
};
int main ()
{
std::array<int, 5> a = { 1, 2, 3, 4, 5 };
std::for_each(a.begin(), a.end(), std::bind2nd(multip(), 2));
//std::copy(a.begin(), a.end(), std::ostream_iterator<int>(std::cout, " "));
system("PAUSE");
return 0;
}
List Library clear() Function in C++
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.
Syntax for List clear() Function in C++
#include <list>
void clear() noexcept;
Complexity
Linear in list::size (destructions).
Iterator validity
All iterators, references and pointers related to this container are invalidated, except the end iterators.
Data races
The container is modified. All contained elements are modified.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* clear() function is used to remove all the elements of the list container, thus making it size 0. */
/* Clear content of the list by list clear() function code example */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> myList;
std::list<int>::iterator i;
myList.push_back (10);
myList.push_back (20);
myList.push_back (30);
cout<<"List before applying clear() function";
for (auto i = myList.begin(); i != myList.end(); ++i)
cout << ' ' << *i;
myList.clear();
for (auto i = myList.begin(); i!= myList.end(); ++i)
cout << ' ' << *i;
cout<<"\nlist is cleared ";
myList.push_back (60);
myList.push_back (70);
cout<<"\nelements in my list are: ";
for (auto i=myList.begin(); i!=myList.end(); ++i)
cout<< ' ' << *i;
return 0;
}
Iterator Library reverse_iterator in C++
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 (this would be the past-the-end element of the reversed range).
Syntax for reverse_iterator in C++
#include <iterator>
template <class Iterator> class reverse_iterator;
Iterator
A bidirectional iterator type.
Or a random-access iterator, if an operator that requires such a category of iterators is used.
Member types
• iterator_type Iterator Iterator's type
• iterator_category iterator_traits<Iterator>::iterator_category Preserves Iterator's category
• value_type iterator_traits<Iterator>::value_type Preserves Iterator's value type
• difference_type iterator_traits<Iterator>::difference_type Preserves Iterator's difference type
• pointer iterator_traits<Iterator>::pointer Preserves Iterator's pointer type
• reference iterator_traits<Iterator>::reference Preserves Iterator's reference type
Member functions
• (constructor) Constructs reverse_iterator object (public member function )
• base Return base iterator (public member function )
• operator* Dereference iterator (public member function )
• operator+ Addition operator (public member function )
• operator++ Increment iterator position (public member function )
• operator+= Advance iterator (public member function )
• operator- Subtraction operator (public member function )
• operator-- Decrease iterator position (public member function )
• operator-= Retrocede iterator (public member function )
• operator-> Dereference iterator (public member function )
• operator[] Dereference iterator with offset (public member function )
Non-member function overloads
• relational operators Relational operators for reverse_iterator (function template )
• operator+ Addition operator (function template )
• operator- Subtraction operator (function template )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* std::reverse_iterator is an iterator adaptor that reverses the direction of a given iterator. In other words, when provided with a bidirectional iterator, std::reverse_iterator produces a new iterator that moves from the end to the beginning of the sequence defined by the underlying bidirectional iterator. */
/* Constructs reverse_iterator object by std::reverse_iterator */
#include <iostream>
#include <iterator>
template<typename T, size_t SIZE>
class Stack {
T arr[SIZE];
size_t pos = 0;
public:
T pop() {
return arr[--pos];
}
Stack& push(const T& t) {
arr[pos++] = t;
return *this;
}
// we wish that looping on Stack would be in LIFO order
// thus we use std::reverse_iterator as an adaptor to existing iterators
// (which are in this case the simple pointers: [arr, arr+pos)
auto begin() {
return std::reverse_iterator(arr + pos);
}
auto end() {
return std::reverse_iterator(arr);
}
};
int main() {
Stack<int, 8> s;
s.push(5).push(15).push(25).push(35);
for(int val: s) {
std::cout << val << ' ';
}
}
List Library assign() Function in C++
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.
Syntax for List assign() Function in C++
#include <list>
//range (1)
template <class InputIterator>
void assign (InputIterator first, InputIterator last);
//fill (2)
void assign (size_type n, const value_type& val);
//initializer list (3)
void assign (initializer_list<value_type> il);
first, last
Input iterators to the initial and final positions in a sequence. The range used is [first,last), which includes all the elements between first and last, including the element pointed by first but not the element pointed by last.
The function template argument InputIterator shall be an input iterator type that points to elements of a type from which value_type objects can be constructed.
n
New size for the container. Member type size_type is an unsigned integral type.
val
Value to fill the container with. Each of the n elements in the container will be initialized to a copy of this value.
Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
il
An initializer_list object. The compiler will automatically construct such objects from initializer list declarators.
This function does not return any value.
Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
In the range version (1), the new contents are elements constructed from each of the elements in the range between first and last, in the same order.
In the fill version (2), the new contents are n elements, each initialized to a copy of val.
In the initializer list version (3), the new contents are copies of the values passed as initializer list, in the same order.
If there are changes in storage, the internal allocator is used (through its traits). It is also used to destroy all existing elements, and to construct the new ones.
Any elements held in the container before the call are either assigned to or destroyed.
Complexity
Linear in initial and final sizes (destructions, constructions).
Iterator validity
All iterators, references and pointers related to this container are invalidated, except the end iterators.
Data races
All copied elements are accessed. The container is modified. All contained elements are modified.
Exception safety
Basic guarantee: if an exception is thrown, the container is in a valid state.
If allocator_traits::construct is not supported with the appropriate arguments for the element constructions, or if the range specified by [first,last) is not valid, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* The list::assign() function is a part of the C++ standard template library. It is used to assign the values to a list and also to copy values from one list to another. */
/* assign new contents to the list container and replace the old one with a new one by List assign() function code example. */
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Initialization of list
list<int> first_list;
// Initializing second list
list<int> second_list;
// Assigning the value 100, 5 times
// to the second_list.
second_list.assign(5, 100);
// Copying second_list to first_list
first_list.assign(second_list.begin(),
second_list.end());
for (int itr : first_list) {
cout << itr << " ";
}
return 0;
}
List Library max_size() Function in C++
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.
Syntax for List max_size() Function in C++
#include <list>
size_type max_size() const noexcept;
Complexity
Constant
Iterator validity
No changes
Data races
The container is accessed. No contained elements are accessed: concurrently accessing or modifying them is safe.
Exception safety
No-throw guarantee: this member function never throws exceptions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* The C++ list::max_size function returns the maximum size the list can reach. The function returns the maximum potential size the list can reach due to known system or library implementation limitations. */
/* get maximum size of the list by list max_size() function code example */
#include <iostream>
#include <list>
using namespace std;
int main (){
list<int> MyList{10, 20, 30, 40, 50};
list<int>::iterator it;
cout<<"The list contains:";
for(it = MyList.begin(); it != MyList.end(); ++it)
cout<<" "<<*it;
cout<<"\nList size is: "<<MyList.size()<<"\n";
cout<<"Maximum size of the List: "<<MyList.max_size()<<"\n";
return 0;
}
List Library push_front() Function in C++
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.
Syntax for List push_front() Function in C++
#include <list>
void push_front (const value_type& val);
void push_front (value_type&& val);
val
Value to be copied (or moved) to the inserted element. Member type value_type is the type of the elements in the container, defined in list as an alias of its first template parameter (T).
This function does not return any value.
The storage for the new elements is allocated using the container's allocator, which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Complexity
Constant
Iterator validity
No changes
Data races
The container is modified. No existing elements are accessed (although see iterator validity above).
Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the container.
If allocator_traits::construct is not supported with val as argument, it causes undefined behavior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* list::push_front() is an inbuilt function in C++ STL which is declared in header file. push_front() is used to push/insert the element in the list container at the front i.e. at the beginning. By pushing a new element at front the already existing first element becomes the second element by making the inserted one the first and the size of the list also increased by 1. */
/* Insert element at beginning by list::push_front() function code example */
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Creating a list
list<int> demoList;
// Adding elements to the list
// using push_back()
demoList.push_back(10);
demoList.push_back(20);
demoList.push_back(30);
demoList.push_back(40);
// Initial List:
cout << "Initial List: ";
for (auto itr = demoList.begin(); itr != demoList.end(); itr++)
cout << *itr << " ";
// Adding elements to the front of List
// using push_front
demoList.push_front(5);
// List after adding elements to front
cout << "\n\nList after adding elements to the front:\n";
for (auto itr = demoList.begin(); itr != demoList.end(); itr++)
cout << *itr << " ";
return 0;
}
C++ Program perform LU Decomposition of a matrix. LU decomposition factors a matrix as the product of a Lower Triangular Matrix and an upper 'triangular matrix'. Code sometimes
This c++ program shows the greatest number between 3 numbers use 'if-else-if' statement. It takes three numbers as input from user and output the greatest number. Enter value first