【发布时间】:2017-08-11 11:36:42
【问题描述】:
我知道,如果我在 std::map 中插入一个值,我可以通过检查插入返回值来获得一个引用插入元素(或之前存在的元素)的迭代器,如下所示:
std::map<int, char> m;
auto ret = m.insert(std::make_pair(1, 'A'));
if (ret.second)
std::cout << "it worked" << std::endl;
// ... now iterations over the map starting at ret.first
但是,我想知道之后操纵获得的迭代器是否合法,例如在失败的情况下分配所需的值。
std::map<int, char> m;
auto ret = m.insert(std::make_pair(1, 'A'));
if (!ret.second)
ret.first->second = 'A'; // assign the value in case it went wrong
我注意到这似乎可行,但我不确定这是否是所需的行为,因为在插入失败的情况下我发现的一切都是使用 operator[] 代替。然而这对我来说不是一个解决方案,因为我需要 insert 之后返回的迭代器,并且由于性能原因我不能使用 insert 和 operator[]。
长话短说: 操作从 std::maps insert() 返回的迭代器引用的数据是否有效?
【问题讨论】:
-
您也可以先使用
std::map::count,而不是尝试插入。 -
@Jonas 但是
std::map::count也有 O(log(N)) 的复杂度,所以在插入失败的情况下,它和m[1] = 'A'一样糟糕,我想避免这种情况。