首页 > 解决方案 > 这两个基于范围的循环有什么区别

问题描述

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;
}

标签: loopsc++11iteratorranged-loops

解决方案


 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/在这里您将获得有关此的更多详细信息


推荐阅读