gpt4 book ai didi

c++ - 常量映射迭代器不会设置为 mymap.begin()

转载 作者:可可西里 更新时间:2023-11-01 16:27:12 25 4
gpt4 key购买 nike

map<string,Shopable*>::iterator it = mymap.begin();

迭代器似乎是常量,但 items.begin() 不返回常量迭代器。或者,这就是我的想法,因为鼠标悬停错误类似于:

"No conversion from 'std::Tree_const_iterator<...> to std::Tree_iterator<...> exists'".

为什么?

最佳答案

const_iterator 用作:

map<string,Shopable*>::const_iterator it = mymap.begin();

从错误来看,很明显 mymap.begin() 返回 const_iterator。这是因为 mymap 在您编写此函数的函数中是 const,如下所示:

void f(const std::map<int,int> & m)
{ //^^^^^ note this

std::map<int,int>::const_iterator it = m.begin(); //m is const in f()
//^^^^^ note this
}

void g(std::map<int,int> & m)
{
std::map<int,int>::iterator it = m.begin(); //m is non-const in g()
}

也就是说,const容器(无论是std::mapstd::vector等)返回const_iterator 和非常量容器返回 iterator

每个容器都有重载函数begin()end()。所以 const 容器调用重载的 begin() 返回 const_iterator 而非 const 容器调用另一个重载的 begin() 返回 iteratorend() 重载函数也是如此。

关于c++ - 常量映射迭代器不会设置为 mymap.begin(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5872685/

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