public member function
<unordered_map>
template <class... Args>pair<iterator, bool> emplace ( Args&&... args );
Construct and insert element
Inserts a new element in the unordered_map if its key is unique. This new element is constructed in place using args as the arguments for the element's constructor.
The insertion only takes place if no element in the container has a key equivalent to the one being emplaced (keys in an unordered_map are unique).
If inserted, this effectively increases the container size by one.
A similar member function exists, insert, which either copies or moves existing objects into the container.
引數
- args
-
Arguments used to construct a new object of the mapped type for the inserted element.
Arguments forwarded to construct the new element (of type
pair<const key_type, mapped_type>
).
This can be one of
- Two arguments: one for the
key, the other for the
mapped value.
- A single argument of a
pair
type with a value for the
key as first member, and a value for the
mapped value as second.
-
piecewise_construct as first argument, and two additional arguments with
tuples to be forwarded as arguments for the
key value and for the
mapped value respectivelly.
See
pair::pair for more info.
返回值
If the insertion takes place (because no other element existed with the same key), the function returns a pair object, whose first component is an iterator to the inserted element, and whose second component istrue.
Otherwise, the pair object returned has as first component an iterator pointing to the element in the container with the same key, andfalseas its second component.
成員型別iterator是一個 forward iterator 型別。
新元素的儲存使用allocator_traits<allocator_type>::construct()分配,這在失敗時可能會丟擲異常(對於預設的 allocator,bad_alloc如果分配請求不成功,則丟擲)。
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// unordered_map::emplace
#include <iostream>
#include <string>
#include <unordered_map>
int main ()
{
std::unordered_map<std::string,std::string> mymap;
mymap.emplace ("NCC-1701", "J.T. Kirk");
mymap.emplace ("NCC-1701-D", "J.L. Picard");
mymap.emplace ("NCC-74656", "K. Janeway");
std::cout << "mymap contains:" << std::endl;
for (auto& x: mymap)
std::cout << x.first << ": " << x.second << std::endl;
std::cout << std::endl;
return 0;
}
|
可能的輸出
mymap contains:
NCC-1701: J.T. Kirk
NCC-1701-D: J.L. Picard
NCC-74656: K. Janeway
|
複雜度
平均情況:常量。
最壞情況:容器大小的線性。
May trigger a rehash (not included).
迭代器有效性
在大多數情況下,插入後容器中的所有迭代器都保持有效。唯一的例外是當容器的增長強制重新雜湊時。在這種情況下,容器中的所有迭代器都將失效。
A rehash is forced if the new container size after the insertion operation would increase above its capacity threshold (calculated as the container's bucket_count multiplied by its max_load_factor).
無論如何,指向 unordered_map 容器中元素的引用都保持有效,即使在 rehash 之後也是如此。