微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

cpp中关键字auto的两个实例

如何解决cpp中关键字auto的两个实例

一个是:

map <int,int> m;
//... some elements inserted
auto i= m.begin();
cout<<(*i).first<<(*i).second;

这里我们需要使用解引用操作符*
第二:

map <int,int> m;
//... some elements inserted
for(auto i: m)
cout<<i.first<<i.second;

为什么我这次不需要使用 * 运算符?
还有一个疑问:

for(auto &i: m)

“&”在这里有什么区别?

解决方法

auto i=m.begin() 会给你迭代器 .. 当你想访问值时,它更像是一个指针(语法上)访问......

for(auto i:m) 会将 m 的当前元素(一对)复制到 i 中,i 是元素的副本,而不是元素本身...

for (auto &i: m) 将在参考上工作,原始地图受到影响

,

如以下代码片段所述,第一个 i 是迭代器类型,而 for 循环中的 i 是 pair 类型。

#include <iostream>
#include <map>

int main()
{
    std::map <int,int> m;
    m[1] = 5;
    m[10] = 60;
    m[100] = 800;
    // Below i is map iterator (std::map<int,int>::iterator)
    auto i = m.begin();
    std::cout << typeid(i).name() << '\n';
    std::cout << (*i).first << " : " << (*i).second << '\n';
    std::cout << i->first << " : " << i->second << '\n';

    for(auto i: m) {
        // Below i is pair<int,int>
        std::cout << typeid(i).name() << '\n';
        std::cout << i.first << " : " << i.second << '\n';
    }
    for(auto& i: m) {
        // Below i is reference of pair<int,int>)
        // modifying this would result in updated values in the map.
        std::cout << typeid(i).name() << '\n';
        std::cout << i.first << " : " << i.second << '\n';
    }
    return 0;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。