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.
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.
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.
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.
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>
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";
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.
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();
Assuming word_count is a map from string to size_t and word is a string, explain the following loop:
while (cin >> word)
++word_count.insert({word, 0}).first->second;
++ (word_count.insert({word, 0}).first->second)
Given a map<string, vector>, write the types used as an argument and as the return value for the version of insert that inserts one element.
std::pair<std::string, std::vector<int>> // argument
std::pair<std::map<std::string, std::vector<int>>::iterator, bool> // return