The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #24
Programming with C++
Iterators, associative containers (cont.)
Warm up
Given the following definition of type student, what container would you use to implement a class roster that allows efficient lookup of a student by their email?
struct student
{
std::string first_name;
std::string last_name;
std::string email;
};
struct class_roster
{
student find_by_email( std::string const& email );
// ???
};
Iterators
Objects with a well-defined interface that enable us to iterate/traverse over elements of a container without knowing the container's underlaying data structure.
In C++, the standard iterator interface is that of a generalized pointer.
std::vector<student> roster1 = { ... };
std::set<student> roster2 = { ... };
for ( auto const& s: roster1 )
std::cout << s << std::endl;
for ( auto const& s: roster2 )
std::cout << s << std::endl;
Iterators (cont.)
for ( auto const& s: roster1 )
std::cout << s << std::endl;
{
auto iter = roster1.begin();
auto end = roster1.end();
for ( ; iter != end; ++iter )
std::cout << *iter << std::endl;
}
v.end()
v.begin()
...
[ begin, end )
— half-open interval aka inclusive/exclusive range
Iterator Operations
Obtaining an iterator to the beginning of a sequence:
Moving forward in a sequence:
Recognizing an end of a sequence:
begin( seq )
++i
i != end( seq )
Accessing the element:
*i
Moving backward in a sequence:
--i
Advance to an nth element (O(1) arithmetics):
i += n, i + n, i -= n, i - n, i - j
Compare iterator position:
i < j, i <= j, i > j, i >= j
Exercise 1
Write a function `find` that takes a vector of strings and a string value to search for and returns an iterator to the matching vector element
-
Open the exercise template
-
Write your code, press Run to test
-
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
-
Click on the corresponding option in the "Lab24 exercises" poll in #general
Associative Container Operations
Container's begin/end iterators.
c.insert(value)
c.erase(key)
c.erase(iter)
c.find(key)
c.count(key)
c.begin()
c.end()
c.empty()
c.size()
c.clear()
Erases all elements from the container.
begin() == end()
Number of elements in the container.
Inserts element(s) into the container.
Removes specified element(s) from the container.
c.erase(first, last)
Number of elements with the specified key.
Iterator to an element with the specified key.
Programming with C++, Fall 2019, Lecture #24
By Aleksey Gurtovoy
Programming with C++, Fall 2019, Lecture #24
Iterators, associative containers (cont.)
- 645