Skip to content

Latest commit

 

History

History
77 lines (58 loc) · 2.81 KB

README.md

File metadata and controls

77 lines (58 loc) · 2.81 KB

Chapter 11. Associative Containers

Exercise 11.1:

Describe the differences between a map and a vector.

A map is a collection of key-value pairs. we can get a value lookup by key efficiently.

A vector is a collection of objects, and every object has an associated index, which gives access to that object.

Exercise 11.2:

Give an example of when each of list, vector, deque, map, and set might be most useful.

  • list : a to-do list. always need insert or delete the elements anywhere.
  • vector : save some important associated data, always need query elements by index.
  • deque : message handle. FIFO.
  • map : dictionary.
  • set : bad_checks.

Exercise 11.5:

Explain the difference between a map and a set. When might you use one or the other?

  • set : the element type is the key type.
  • map : we should use a key-value pair, such as {key, value} to indicate that the items together from one element in the map.

I use set when i just need to store the key, In other hand, I would like use map when i need to store a key-value pair.

Exercise 11.6:

Explain the difference between a set and a list. When might you use one or the other?

set is unique and order, but list is neither. using which one depend on whether the elements are unique and order to store.

Exercise 11.15:

What are the mapped_type, key_type, and value_type of a map from int to vector?

  • mapped_type : vector
  • key_type : int
  • value_type : std::pair<int, vector>

Exercise 11.16:

Using a map iterator write an expression that assigns a value to an element.

std::map<int, std::string> map;
map[25] = "Alan";
std::map<int, std::string>::iterator it = map.begin();
it->second = "Wang";

Exercise 11.17:

Assuming c is a multiset of strings and v is a vector of strings, explain the following calls. Indicate whether each call is legal:

copy(v.begin(), v.end(), inserter(c, c.end())); // legal
copy(v.begin(), v.end(), back_inserter(c)); // illegal, no `push_back` in `set`.
copy(c.begin(), c.end(), inserter(v, v.end())); // legal.
copy(c.begin(), c.end(), back_inserter(v)); // legal.

Exercise 11.19:

Define a variable that you initialize by calling begin() on the multiset named bookstore from 11.2.2 (p. 425). Write the variable’s type without using auto or decltype.

using compareType = bool (*)(const Sales_data &lhs, const Sales_data &rhs);
std::multiset<Sales_data, compareType> bookstore(compareIsbn);
std::multiset<Sales_data, compareType>::iterator c_it = bookstore.begin();