如何从新插入的对(到映射)返回引用对

How does one return a reference pair from a newly inserted pair (to a map)?

本文关键字:映射 引用 返回 插入 新插入      更新时间:2023-10-16

如何正确有效地从新插入的pair返回pair到映射?

inline pair<unsigned int, T> *createObj(unsigned int UID){
    static pair<unsigned int, T> ret;
    objList.insert(pair<unsigned int, T>(UID, T()));
    if (UID_Counter <= UID) 
        UID_Counter = UID+1; 
    ret = make_pair(UID, objList.find(UID)->second);
    return &ret;
}
上面的

返回一个要使用的对象,但是无论我在ret中做了什么改变,都不会在映射中的"实对"中改变…

基本上我想实现的是:

  1. 将新的对象Z插入映射A
  2. ("子"类)更改返回的对象Z
  3. 中的内容
  4. 在每个更新周期中,遍历map A中的对象,并在更新时使用加载到对象"A-Z"中的实际数据…

您正在使用的insert的特定过载返回std::pair<iterator, bool>。特别是,这对元素的第一个成员是一个迭代器,指向新插入的元素或已经存在的元素。因此:

pair<const unsigned int, T>&
createObj(unsigned int UID)
{
    auto inserted = objList.insert(pair<unsigned int, T>(UID, T()));
    if (UID_Counter <= UID) 
        UID_Counter = UID+1; 
    return *inserted.first;
}

注意,我返回一个引用,你返回一个指针,键类型是const unsigned int,而不是unsigned int。您也可以使用map_type::value_type(其中map_type是您的容器类型)。

如果你想知道为什么你的代码不能工作,这是因为你在ret中存储了一个映射对象的副本,所以通过你返回的指针进行的任何修改都只会影响那个副本。