map::emplace

插入就地构造的元素 (复制或移动该操作不执行) 到映射中。

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

参数

参数

说明

args

转发的参数构造要插入的元素添加到映射,除非它已经包含值相同地排序的元素。

返回值

一个pair whose bool 组件如果已插入那就是真的, 如果映射已经包含值相同地排序的元素就是假的. 返回值对点的迭代器组件指向新插入的元素如果 bool 组件为真,或到现有元素如果 bool 组件为假.

要进入 pair pr的迭代器组件, 使用 pr.first; 要废除它, 使用 *pr.first. 使用 pr.second来访问bool组件。 有关示例,请参见示例之后代码本文中。

备注

没有迭代器或通过此函数的引用是无效的。

在建立期间,如果抛出了异常,容器的状态将不会被修改。

value_type 一个元素是一对, 使元素值为一个有序对,第一个组件与键值相同和第二组件与元素数据值相同。

示例

// map_emplace.cpp
// compile with: /EHsc
#include <map>
#include <string>
#include <iostream>

using namespace std;

template <typename M> void print(const M& m) {
    cout << m.size() << " elements: ";

    for (const auto& p : m) {
        cout << "(" << p.first << ", " << p.second << ") ";
    }

    cout << endl;
}

int main()
{
    map<int, string> m1;

    auto ret = m1.emplace(10, "ten");

    if (!ret.second){
        auto pr = *ret.first;
        cout << "Emplace failed, element with key 10 already exists."
            << endl << "  The existing element is (" << pr.first << ", " << pr.second << ")"
            << endl;
        cout << "map not modified" << endl;
    }
    else{
        cout << "map modified, now contains ";
        print(m1);
    }
    cout << endl;

    ret = m1.emplace(10, "one zero");

    if (!ret.second){
        auto pr = *ret.first;
        cout << "Emplace failed, element with key 10 already exists."
            << endl << "  The existing element is (" << pr.first << ", " << pr.second << ")"
            << endl;
    }
    else{
        cout << "map modified, now contains ";
        print(m1);
    }
    cout << endl;
}

Output

map modified, now contains 1 elements: (10, ten)

Emplace failed, element with key 10 already exists.
  The existing element is (10, ten)

要求

标头: <map>

命名空间: std

请参见

参考

<map>

map 类

标准模板库