C++:问题 vector STL

标签 c++ function vector stl

我确实通过调用名为 getDivisors 的函数得到了除数并返回由容器格式化的值 vector<int> .

因为我是 C++ 的新手容器,我尝试使用迭代器通过 for 循环打印我的除数整数。但是,在我看来,这似乎太复杂了。 有什么简单的方法可以在 vector 中显示存储的整数 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 的编译器中,您可以使用 autoRanged-based for loop

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

i here is not an iterator, it's the container template type which in your case is an int

指针是一种 iterator特别是 random access iterator .迭代器被设计为指针的抽象,带有 *->++-- 等运算符. 用于访问 containers .

对于 C++ 程序员,cplusplus.com是你的 friend 。

关于C++:问题 vector STL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332227/

相关文章:

c++ - 是否使用静态 constexpr 变量 odr?

c++ - 当变量是右值引用时自动从局部变量移动

c++ - 在构造函数定义中调用函数后收到 Segmentation Fault 11 错误?

python - 未绑定(bind)本地错误: local variable 'y' referenced before assignment in Pandas

c++ - 迭代 vector/ map 数据结构 C++

c++ - 将 mem_fun 存储在标准容器中

c++ - win32程序如何使用自己的ico文件

c++ - TCP/IP 和设计网络应用程序

html - VBA 函数不返回 HTMLElementCollection 对象

c++ - 给出错误 "not declared in this scope"的结构 vector