繁体   English   中英

C ++:问题向量STL

[英]C++:questions vector 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 did it is pointer type? Could you explain it more about it? I was confused that the compilers show the error message when I did it is pointer type? Could you explain it more about it? I was confused that the compilers show the error message when I didnot it is pointer type? Could you explain it more about it? I was confused that the compilers show the error message when I did `

以下是我的简单代码。

#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基于Ranged的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM