这两个基于范围的循环有什么区别
Whats the difference between these two range based 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;
}
如果我使用下面的代码而不是上面的代码,上面的代码现在不能工作,它工作得很好。我不知道为什么会这样,请告诉我有什么区别。
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<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;
}
在这种情况下,我们创建了一个 pair 类型的变量,它将映射值复制到其中,可以通过 (.) 运算符访问。
需要注意的重要一点是,在第一种情况下,我们通过指针访问,在这里我们复制 map 变量,然后访问 it.so 如果我们使用它变量更改我们的值,那么更改也会反映在实际 map 中,但在第二种情况下情况有任何变化
确实影响了我们的实际地图。
你也可以像这样使用反向迭代器
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/ 在这里你会得到更多关于这个的细节
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;
}
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;
}
在这种情况下,我们创建了一个 pair 类型的变量,它将映射值复制到其中,可以通过 (.) 运算符访问。 需要注意的重要一点是,在第一种情况下,我们通过指针访问,在这里我们复制 map 变量,然后访问 it.so 如果我们使用它变量更改我们的值,那么更改也会反映在实际 map 中,但在第二种情况下情况有任何变化 确实影响了我们的实际地图。
你也可以像这样使用反向迭代器
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/ 在这里你会得到更多关于这个的细节