如何获得非const迭代器 [英] How get non-const iterator
问题描述
std::map<char,int> dict;
...
auto pmax = dict.begin(); // here i get const iterator
我可以明确指出常数类型?
Can I "explicitly indicate" that the value obtained is a non-constant type?
推荐答案
查看您的代码,你基本上实现了 std :: max_element
。因此,您可以将最后一个输出行重写为:
Looking at your code, you are basically implementing std::max_element
. So you could rewrite your last output line to:
std::cout << std::max_element(begin(dict), end(dict),
[](decltype(*begin(dict)) a, decltype(*begin(dict)) b) {
return a.second < b.second;
})->first << std::endl;
诚然, decltype(* begin(dict))
是丑陋的,这希望可以通过C ++ 1y中的通用lambdas补救。
Admittedly, the decltype(*begin(dict))
is ugly, which hopefully will be remedied by generic lambdas in C++1y.
关键是,无论你是否有一个 map :: iterator
或 map :: const_iterator
当你解除引用时,结果将是 std :: pair
与 const key_type
作为第一个参数。所以,即使你有两个迭代器
s it1,it2
到可变数据(例如,通过 map :: begin()
),您不能重新分配这些迭代器引用的完整对
。因此, * it1 = * it2
将无法正常工作,因为您试图覆盖 mapped_type
const key_type
。
The point is, that regardless of whether you have a map::iterator
or map::const_iterator
when you dereference it, the result will be a std::pair
with a const key_type
as first argument. So, even if you have two iterator
s it1, it2
to mutable data (e.g., acquired via map::begin()
), you can not re-assign the complete pair
that is referenced by those iterators. Thus, *it1 = *it2
won't work, because you are trying to overwrite the mapped_type
and the const key_type
.
这篇关于如何获得非const迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!