[英]Assigning a const_iterator to an iterator
我有下面的代碼片段(你可以在這里運行: 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<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分配給迭代器總是拋出錯誤嗎?
實際上std::set<T>::iterator
與std::set<T>::const_iterator
因為std::set
的元素是不可變的。 它沒有可變的迭代器類型。
這不是std::map
的情況,這就是您觀察不同行為的原因。
來自 C++ 17 標准(26.2.6 關聯容器)
關聯容器的 6 迭代器屬於雙向迭代器類別。 對於值類型與鍵類型相同的關聯容器,iterator 和 const_iterator 都是常量迭代器。 未指定 iterator 和 const_iterator 是否為同一類型。
您不能修改集合元素。 鍵必須是const
以確保set
承諾的不變性:元素是有序且唯一的。 map
的元素也已排序,但您可以修改元素的映射值(鍵也是const
)。 std::map<A,B>
元素是std::pair<const A,B>
。
在cppreference 上,您可以閱讀std::set
迭代器的成員別名是
迭代器常量 LegacyBidirectionalIterator
const_iterator 常量 LegacyBidirectionalIterator
它們都是常量迭代器。
另一方面,對於std::map
它們是:
迭代器 LegacyBidirectionalIterator
const_iterator 常量 LegacyBidirectionalIterator
將const_iterator
分配給非常量的迭代器是錯誤的。 它喜歡嘗試投const
路程分配一個指向const
的指針非const。 這是行不通的,因為您無法使無法修改的內容成為可修改的。 那會破壞常量正確性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.