loops - 这两个基于范围的循环有什么区别
问题描述
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<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/在这里您将获得有关此的更多详细信息
推荐阅读
- go - 更改 2D 数组变量也会更改原始 2D 数组变量。为什么?
- windows - Powershell - 嵌套 IF 在 Do-While 循环中无法正确执行
- php - 在条件下重用表单 HTML 元素
- protocol-buffers - 为什么 protobuf 的 FieldMask 使用字段名而不是字段号?
- cross-reference - 检索给定年份科学论文的引用次数
- python - 删除所有邀请的事件,除非它来自某个公会
- python - 在python中,如何根据具有下限和上限的查找表对范围进行分类
- java - 如果存在 JNDI 资源,则 CDI 有条件地生成/覆盖 bean
- python - 手动更改 PKG-INFO?
- ruby - UTF-8 和 CJK 不显示在 Ruby (Windows) 中