【发布时间】:2021-02-11 05:21:28
【问题描述】:
我有下面的 sn-p 代码(你可以在这里运行:http://coliru.stacked-crooked.com/a/2f62134b5c125051)
#include <iostream>
#include <set>
#include <map>
int main()
{
std::set<std::pair<const int, const int>> const mySet{{0,0}}; // value_type = std::pair<const int, const int>
for (std::set<std::pair<const int, const int>>::iterator it = mySet.cbegin(); it != mySet.cend(); ++it)
{
std::cout<<"set it = " << it->first << " " << it->second << std::endl;
}
std::map<const int, const int> const myMap{{0,0}}; // value_type = std::pair<const int, const int>
for (std::map<const int, const int>::iterator it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout<<"map it = " << it->first << " " << it->second << std::endl;
}
}
谁能解释一下为什么对于 std::set 下面没有抛出任何错误:
std::set<std::pair<const int, const int>>::iterator it = mySet.cbegin();
而对于 std::map 下面会抛出错误(从 _Rb_tree_const_iterator<:pair int const> > 到 _Rb_tree_iterator<:pair int const> >) 符合预期:
std::map<const int, const int>::iterator it = myMap.cbegin();
std::set 是如何工作的?将 const_iterator 分配给 iterator 不应该总是抛出错误吗?
【问题讨论】:
-
如果你把
const放在std::map或std::set前面,我不认为你能做你正在做的事情。你会得到一个编译器错误。 -
另外,你的 const 并不直接应用于你的向量或集合的元素,它应用于你的
std::pair中的元素,所以即使你的向量有一个非常量迭代器,你仍然无法更改对的值。
标签: c++ c++11 iterator set const-iterator