【问题标题】:Whats the difference between these two range based loops这两个基于范围的循环有什么区别
【发布时间】:2020-10-14 16:49:39
【问题描述】:
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;
}

如果我使用下面的代码代替上面的代码,上面的代码现在不起作用,它工作得很好。我知道为什么会这样,请告诉我有什么区别。

int main()
{             
       map<float,float>m;
       //Input some value in m
        for(auto it:m)
        {
           cout<<it.first<<" "<<it.second;
        }

    return 0;
}

【问题讨论】:

  • 您的意思是除了循环的方向之外,您不会在第一个循环中使用地图中的第一个元素,第二个循环迭代的是 values 而不是迭代器,在第一个循环中您使用了错误的成员访问器运算符,并且您在第一个循环中取消引用 end 迭代器(这会导致 未定义的行为)?
  • 迭代器必须被取消引用。 it-&gt;ff
  • 根据定义,只有第二个是“基于范围的”。
  • @HolyBlackCat 在这两种情况下auto it 类型有什么区别
  • 是的,在第一个中它被推导出为map&lt;float,float&gt;::iterator(因此您需要使用-&gt; 而不是.),在第二个中它使用 取消引用 map&lt;float,float&gt;::iterator,即pair&lt;const float, float&gt;

标签: loops c++11 iterator ranged-loops


【解决方案1】:
 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<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/ 在这里您将获得有关此的更多详细信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 2013-11-14
    相关资源
    最近更新 更多