我有以下的代码片段(你可以在这里运行:http://coliru.stacked-crooked.com/a/2f62134b5c125051)
有人能否解释一下为什么对于 std::set ,下面的代码不会抛出任何错误:
对于 std::map,以下代码会抛出错误(从_Rb_tree_const_iterator<std::pair<const int, const int> >到_Rb_tree_iterator<std::pair<const int, const int> >没有已知的转换),这是预期的:
它对于 std::set 是如何工作的?将一个const_iterator分配给iterator不应该总是抛出错误吗?
#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<std::pair<const int, const int> >到_Rb_tree_iterator<std::pair<const int, const int> >没有已知的转换),这是预期的:
std::map<const int, const int>::iterator it = myMap.cbegin();
它对于 std::set 是如何工作的?将一个const_iterator分配给iterator不应该总是抛出错误吗?
std::map
或者std::set
前面加上const
,我觉得你将无法完成你正在做的事情。你会得到一个编译器错误。 - santahoparstd::pair
中的元素,因此即使使用非const迭代器遍历你的向量,你仍然无法更改这些对的值。 - santahopar