【问题标题】:Two instances of keyword auto in cppcpp中关键字auto的两个实例
【发布时间】:2021-06-20 01:24:36
【问题描述】:

第一个是:

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(); std::map&lt;int, int&gt;::iterator i = m.begin (); | for(auto i: m) for (std::map&lt;int, int&gt;::value_type i : m) | for(auto &amp;i: m) for (std::map&lt;int, int&gt;::value_type&amp; i : m)
  • 什么是 value_type ?
  • auto 只是自动为您推断类型。在第一个示例中,您有一个指向键值对的迭代器,在第二个示例中没有迭代器。只是一个键值对。另外,您应该使用i-&gt;first 而不是(*i).first
  • @super 谢谢。这真的很有帮助!

标签: c++ for-loop iterator maps auto


【解决方案1】:

正如下面代码 sn-p 中所解释的,第一个 i 是迭代器类型,而 for 循环中的 i 是对类型。

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

【讨论】:

  • 谢谢米塔尔!有帮助
【解决方案2】:

auto i=m.begin() 将为您提供迭代器 .. 当您想要访问值时,它的访问更像是一个指针(在语法上)......

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

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

【讨论】:

  • 好的。所以'i'就像一个指向新对的指针。我说的对吗?
  • i=m.begin() 给你迭代器,调用迭代器指针是不合理的。现在是阅读迭代器 cplusplus.com/reference/iterator 的好时机.....迭代器更多地用于容器......或者您在谈论 for(auto & i:m) 吗??
  • 谢谢,有帮助
  • :) 欢迎,如果您满意,请接受答案并关闭。快乐编码
猜你喜欢
  • 2011-04-16
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 2013-07-15
相关资源
最近更新 更多