【问题标题】:How to understand deque <int> :: iterator it;如何理解 deque <int>::iterator 呢;
【发布时间】:2021-07-15 06:07:16
【问题描述】:

这行注释是什么意思?详情见下方评论:

#include <iostream>
#include <deque>
  
using namespace std;
  
void showdq(deque <int> g)
{
    deque <int> :: iterator it; /*scope resolution operator means we're getting this obj from this scope, angle bracket is used for template, it seems to be an object, but what does the word iterator doing here? 
    Deque<int>g is also passed as value, this could be avoided if it was passed as reference right? I'll delete this once i got the answer, thank you!*/

    for (it = g.begin(); it != g.end(); ++it)
        cout << '\t' << *it;
    cout << '\n';
}

【问题讨论】:

标签: c++ stl deque


【解决方案1】:

这似乎是一个家庭作业问题,所以我会尝试给你指点而不是你提交的答案

deque <int> :: iterator it; 
/*scope resolution operator means we're getting this obj from this scope, 
angle bracket is used for template, it seems to be an object, 
but what does the word iterator doing here? 

:: 范围解析运算符意味着您正在寻找在范围名称中定义的名称(:: 之前的名称)。例如。只是 ::iteratoriterator 将是在全局范围内找到的名称。

所以这里有一个作用域deque&lt;int&gt;::,但是在全局作用域中没有名称deque&lt;int&gt;,这就是为什么你会在第四行看到using namespace stdThis is considered bad practice.

所以让我们把它读作std::queue&lt;int&gt;::iterator

因此,在查找名称 iterator 时,您最好查阅 https://en.cppreference.com/w/cpp/container/deque 的文档

您会发现您正在查看 std::queue 及其成员(它包含的名称)。这些成员描述了不同的事物、值、函数类型等等。找到成员类型迭代器,看看它说了什么。

现在您只需了解迭代器是什么,它的行为类似于https://en.cppreference.com/w/cpp/iterator

请注意后面代码中应用于it 的运算符。你看it = ...it != ...++it*it,它们的含义和功能在链接文档中都有描述。

【讨论】:

    【解决方案2】:

    也许不是您问题的答案,而是对未来的提示。如果你不想关心迭代器,你总是可以使用 for each 循环。

    for (auto value: g) {
        cout << '\t' << value;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      相关资源
      最近更新 更多