这两个基于范围的循环有什么区别


int main()
{             
map<float,float>m;
//input some value in m
for(auto it=m.end();it!=m.begin();it--)
{
cout<<it.first<<" "<<it.second;

}

return 0;
}

如果我使用下面的代码代替上面的代码,上面的代码现在不起作用,它工作得很好。Idk 为什么会发生这种情况,请告诉我有什么区别。

int main()
{             
map<float,float>m;
//Input some value in m
for(auto it:m)
{
cout<<it.first<<" "<<it.second;
}
return 0;
}
map<float , float> m;
auto it=m.end(); // here m.end() will return a pointer of after the last element
it--; //now this points the last element
for(;it!=m.begin();it--)
{   
cout<<it->first<<" "<<it->second<<"n"
cout<< (*it).first<<" " <<(*it).second<<"n"
}
// this for the first element because m.begin() points to the first element
cout<<it->first<<" "<<it->second<<"n"
cout<< (*it).first<<" " <<(*it).second<<"n"

在这里,我们的 it 变量是指向 map 元素的指针类型,这就是为什么需要使用取消引用 (( 运算符的原因。 指针的一个有趣属性是它们可用于访问它们直接指向的变量。这是通过在指针名称前面加上取消引用运算符 (( 来完成的。运算符本身可以理解为"指向的值"。

而在另一种情况下

map<float,float>m;
//Input some value in m
for(auto it:m)
{
cout<<it.first<<" "<<it.second;
}
// we can also write it as 
for(pair<float,float> it : m)
{
cout<<it.first<<" "<<it.second;
}

在这种情况下,我们创建一个成对类型的变量,该变量复制其中的映射值,该值可以通过 (.( 运算符访问。 需要注意的重要一点是,在第一种情况下,我们通过指针访问,在这里我们复制 map 变量,然后访问 it.so 如果我们使用 it 变量更改我们的值,那么更改也会反映在实际地图中,但在第二种情况下任何更改 确实会影响我们的实际地图。

你也可以像这样使用反向迭代器

map<float,float>m;
//input some value in m
for(auto it=m.rbegin();it!=m.rend();it++)
{
count<<it->first<<" "<<it->second;

}

http://www.cplusplus.com/reference/map/map/begin/在这里您将获得有关此内容的更多详细信息

最新更新