当前位置:网站首页>Std:: Map empty example

Std:: Map empty example

2022-06-13 05:01:00 Snow * sleet * snow

emplace 

emplace The operation is from C++11 Start introducing new features ,emplace The operation is to construct elements directly through parameters instead of copying elements into containers, which can reduce copying and improve performance . about map It's not emplace_front、emplace_after、emplace_back These operations are .

std::map<Key,T,Compare,Allocator>::emplace

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

(since C++11)

Inserts a new element into the container constructed in-place with the given args if there is no element with the key in the container.

Note that the return value is also a std::pair

#include <iostream>
#include <utility>
#include <string>
#include <map>
 
int main()
{
    std::map<std::string, std::string> m;
 
    // uses pair's move constructor
    // Use mobile construction 
    m.emplace(std::make_pair(std::string("a"), std::string("a")));
 
    // uses pair's converting move constructor
    // Use implicit conversion to move constructors , The difference from the previous one is the “a” It will be implicitly converted to std::string
    m.emplace(std::make_pair("b", "abcd"));
 
    // uses pair's template constructor
    // Use template construction 
    m.emplace("d", "ddd");
 
    // uses pair's piecewise constructor
    m.emplace(std::piecewise_construct,
              std::forward_as_tuple("c"),
              std::forward_as_tuple(10, 'c'));
    // as of C++17, m.try_emplace("c", 10, 'c'); can be used
 
    for (const auto &p : m) {
        std::cout << p.first << " => " << p.second << '\n';
    }
}

Output :

a => a
b => abcd
c => cccccccccc
d => ddd

原网站

版权声明
本文为[Snow * sleet * snow]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280516196867.html