C++:问题向量 STL.



我通过调用名为 getDivisors 的函数并返回由容器vector<int>格式化的值来获取除数。

由于我是C++容器的新手,因此我尝试使用迭代器通过 for 循环打印除数整数。但是,在我看来,这似乎太复杂了。有没有简单的方法可以在向量STL中显示存储的整数?

我不明白为什么迭代器变量it is pointer type? Could you explain it more about it? I was confused that the compilers show the error message when I didnot它"

以下是我的简单代码。

#include <iostream>
#include <vector>
using namespace std;
vector<int> getDivisors(int input)
{
    vector<int> divisors;
    divisors.push_back(1); //default
    for (int i = 2; i < input; i++){
        if (input%i == 0){
            divisors.push_back(i);
        }
    }
    return divisors;
}
void solve()
{
    int input;
    cin >> input;
    vector<int> divisors = getDivisors(input);
    for (vector<int>::iterator it = divisors.begin(); it != divisors.end(); ++it)
    {
        cout << *it << endl;
    }
}

int main(void)
{
    int num;
    cin >> num;
    for (int i = 0; i < num; i++){
        solve();
    }
    return 0;
}

你没有提到你正在使用哪个编译器,但在C++11兼容编译器中,你可以使用auto和基于范围的for循环

for (auto i : divisors)
{
    cout << i << endl;
}

i这里不是迭代器,而是容器模板类型,在您的情况下是int

指针是一种迭代器,特别是随机访问迭代器。迭代器被设计为指针的抽象,带有*->++--等运算符来访问容器。

对于C++程序员来说,cplusplus.com 是你的朋友。

它不是一个指针,它是一个迭代器。它重写operator *以提供类似指针的行为。您可以阅读有关C++STL的更多信息来理解这一点。

如果您使用的是 C++11 或更高版本,请使用以下命令:

for (auto x : divisors) cout << x << endl;

迭代器是方便的抽象,有助于访问容器。它们不是指针。

您必须注意的一件事是,如果与之关联的容器发生重大更改,迭代器可能会失效。

在继续之前,先读一本关于STL的好书,并掌握正确的基础知识。这是一个入门,但它只能做这么多。
http://www.cprogramming.com/tutorial/stl/iterators.html

最新更新