如何从新插入的对(到映射)返回引用对
How does one return a reference pair from a newly inserted pair (to a map)?
如何正确有效地从新插入的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中做了什么改变,都不会在映射中的"实对"中改变…
基本上我想实现的是:
- 将新的对象Z插入映射A
- ("子"类)更改返回的对象Z 中的内容
- 在每个更新周期中,遍历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
中存储了一个映射对象的副本,所以通过你返回的指针进行的任何修改都只会影响那个副本。
相关文章:
- 智能指针作为无序映射键,并通过引用进行比较
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 从函数返回对映射的引用
- 为什么我不能返回带有透明函子的法线映射引用?
- 通过指针或引用将映射传递给函数?
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- 映射/集迭代器不可取消引用 (C++) - 调试断言失败
- 取消引用映射迭代器时返回对临时的引用
- 有没有办法在不使用循环的情况下非具体地引用映射中的每个值?C++
- lambda 和映射,引用参数 - 编译错误
- 将引用对具有shared_ptr作为值的映射转换为对具有shared_ptr const 作为值的映射的引用
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 使用双迭代器引用映射中的列表
- 在消息映射中创建按钮和引用
- c++存储映射元组的引用,以便在另一个函数中使用
- 由引用集/映射迭代器传递的迭代器不可取消引用
- 本机C++类与 WinRT 组件(引用类)之间的自动映射
- 返回模板映射值作为引用
- SWIG 不可变标准::映射引用
- 同一个类使用的映射引用类