The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #25
(More) sequence containers, generic algorithms
A linear collection of objects, guarantees that the elements are located in a continuous block of memory.
v[0]
v[1]
v[n-1]
...
v.capacity()
v.size()
iter
v.capacity()
v.size()
iter
42
auto iter = numbers.begin() + 1;
numbers.insert( iter, 42 );
list<T>
Doubly-linked list / #include <list>
O(1) insertion/deletion anywhere in the list
Bidirectional iteration (++iter, --iter)
forward_list<T>
Singly-linked list / #include <forward_list>
O(1) insertion/deletion anywhere in the list
Forward iteration only (++iter)
More space-efficient then list<T>
deque<T>
array<T,n>
Doubly-ended queue / #include <deque>
O(1) insertion/deletion at the front/back, O(n) insertion/deletion in the middle
Random-access iteration (++iter, --iter, iter += n)
Static contiguous array / #include <array>
Can't be resized
Random-access iteration (++iter, --iter, iter += n)
Problem: find the first matching element in a sequence container
Solution 1:
Solution 2:
Solution 3:
for ( auto& n: numbers )
if ( n == 33 ) {
// ...
break;
}
for ( auto i = numbers.begin(); i != numbers.end(); ++i )
if ( *i == 33 ) {
// ...
break;
}
auto i = find( numbers.begin(), numbers.end(), 33 );
// ...
auto i = find( first, last, v );
Returns an iterator the first element that is equal to v.
auto n = count( first, last, v );
Returns the number of elements that are equal to v.
fill( first, last, v );
Assigns the given value to all the elements in the range.
auto i = adjacent_find( first, last );
Returns an iterator to the first of the first pair of identical elements.
auto i = copy( first, last, dest );
Copies the elements in the range to another range beginning at dest.
replace( first, last, oldv, newv );
Replaces all elements that are equal to oldv with newv.
reverse( first, last );
Reverses the order of the elements in the range.
auto i = remove( first, last, v );
Removes all elements that are equal to v, returns a past-the-end iterator for the new range of values.
auto [i, j] = equal_range( first, last, v );
Removes all elements that are equal to v, returns a past-the-end iterator for the new range of values.
auto i = find_first_of( first, last, v_first, v_last );
Returns an iterator the first element that is equal to any element in [ v_first, v_last ).
std::back_inserter( c );
Returns a "back inserter" iterator for c, which appends to the end of c when the iterator is dereferenced and consequently assigned to.
std::front_inserter( c );
Returns a "front inserter" iterator for c, which appends to the beginning of c when the iterator is dereferenced and consequently assigned to.
std::inserter( c, pos );
Returns an "inserter" iterator for c, which inserts elements into c at the position pos when the iterator is dereferenced and consequently assigned to.