C++ std::set emplace 返回值 first second

本文通过示例详细介绍了C++中set容器的emplace成员函数,用于插入元素。当元素不存在时,emplace会成功插入并返回迭代器指向新元素;若元素已存在,返回迭代器指向已有的元素。示例展示了当尝试插入已存在的元素时,emplace如何工作以及如何检查插入结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

emplace返回值


一个pair 

  • 逻辑组件如果已插入那就是真的, 如果映射已经包含值相同地排序的元素就是假的.  
  • 返回值的迭代器元素对返回插入新元素的地址 (如果 bool 元素为 true) 或已找到其中的元素 (如果 bool 元素是假)。 

If the function successfully inserts the element (because no equivalent element existed already in the set), the function returns a pair of an iterator to the newly inserted element and a value of true.

Otherwise, it returns an iterator to the equivalent element within the container and a value of false.

Member type iterator is a bidirectional iterator type that points to an element.
pair is a class template declared in <utility> (see pair).

set::emplace - C++ Reference

// set_emplace.cpp
// compile with: /EHsc
#include <set>
#include <string>
#include <iostream>

using namespace std;

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

    for (const auto& p : s) {
        cout << "(" << p << ") ";
    }

    cout << endl;
}

int main()
{
    set<string> s1;

    auto ret = s1.emplace("ten");

    if (!ret.second){
        cout << "Emplace failed, element with value \"ten\" already exists."
            << endl << "  The existing element is (" << *ret.first << ")"
            << endl;
        cout << "set not modified" << endl;
    }
    else{
        cout << "set modified, now contains ";
        print(s1);
    }
    cout << endl;

    ret = s1.emplace("ten");

    if (!ret.second){
        cout << "Emplace failed, element with value \"ten\" already exists."
            << endl << "  The existing element is (" << *ret.first << ")"
            << endl;
    }
    else{
        cout << "set modified, now contains ";
        print(s1);
    }
    cout << endl;
}

set::emplace - 游戏蛮牛 - C++中文翻译用户手册 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

软件工程小施同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值