gpt4 book ai didi

c++ - 将 const_iterator 分配给迭代器

转载 作者:行者123 更新时间:2023-12-03 06:56:01 24 4
gpt4 key购买 nike

我有以下代码片段(您可以在这里运行: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 > 的转换_Rb_tree_iterator > ) 如预期:

std::map<const int, const int>::iterator it  = myMap.cbegin();

std::set 是如何工作的?将 const_iterator 分配给 iterator 不应该总是抛出错误吗?

最佳答案

在实践中std::set<T>::iteratorstd::set<T>::const_iterator相同因为std::set的元素是不可变的。它没有可变迭代器类型。

std::map 不是这种情况这就是为什么您会观察到不同的行为。

关于c++ - 将 const_iterator 分配给迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64579702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com