小编Nat*_*one的帖子

std::unordered_map::insert 与 std::unordered_map::operator[]

我有一个 unordered_map 类型的容器,如果我想向地图添加元素,我想确认应该使用哪个版本。我希望它用新出现的值覆盖旧值(如果存在),如果不存在则添加它。

我看到 insert 会在元素退出时添加该元素,并且还会返回一对迭代器和 bool,其中 bool 指示插入是否成功。我还看到,operator[] 如果元素不存在则添加该元素,如果存在则覆盖它。

我的问题基本上是我是否应该使用operator[]来达到这个目的,或者是否有任何我没有考虑到的问题。另外,如果我对这些方法的理解有误,请纠正我。

这就是我要做的。Data 是存储类型 int 的作用域枚举

void insertData(const Data _Data, const int _value)
{
 int SC_val = static_cast<int>(_Data);
 //sc val is now the integer value of the Data being added

 //returns a pair of iterator and bool indicating whether the insert was successful
auto ret = baseData.insert(std::pair<int,int>(SC_val,_value));

 if (ret.second == false)
 {//if the insert was not successful(key already exists)
     baseData[ret.first->first] = _value;
 }
}
Run Code Online (Sandbox Code Playgroud)

或者我应该这样做

int index = static_cast<int>(_Data);

baseData[index] = …
Run Code Online (Sandbox Code Playgroud)

c++ methods std

1
推荐指数
1
解决办法
4456
查看次数

标签 统计

c++ ×1

methods ×1

std ×1