N
N
Nexeon2016-01-15 14:17:38
C++ / C#
Nexeon, 2016-01-15 14:17:38

How to add all elements from a vector to a multimap container under a specific key?

Good afternoon. Let's say there is a vector:

vector<string> names = {"Ivan", "Alexandr", "Kirill", "Victor"};

And there is also a container of the multimap type:
multimap<int, string> users;
How to add all elements of the names vector to the users map under a certain key?
For example, I want the key[1] to have the values ​​"Ivan", "Alexandr", "Kirill", "Victor".
Using insert() with an iterator of the beginning and end of the vector will not work, there is an option to iterate over the elements of the vector:
for (auto &i :  names) {
users.insert({1, i}); //добавляем имена в группу 1 (добавляем элемент вектора как значение-ключа для ключа[1])
}

But are there more economical ways or alternatives?
PS I'm doing this for practice, I'm still learning cpp

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ananiev, 2016-01-15
@SaNNy32

multimap<int, vector<string>> users;

M
Mercury13, 2016-01-15
@Mercury13

If you need multimap, I don't see any other way. But if there are a lot of elements, it is worth using a hint (the position parameter, where the element will approximately stand). Something like (did not check in the compiler, the code is almost guaranteed to be incorrect).

if (!names.empty()) {
    Users::const_iterator hint = users.upper_bound(1);
    for (auto &i :  names) {
      users.insert(hint, {1, i});
    }
}

Please note that when switching from 03 to 11, the meaning of the hint has changed, here is the version for 11.
PS Sorry, the code for the hint can be made simpler. After inserting and ++ hint will remain the same.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question