我确实通过调用名为 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 did
它not
它`
下面是我的简单代码。
#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-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 anint
指针是一种 iterator特别是 random access iterator .迭代器被设计为指针的抽象,带有 *
、->
、++
、--
等运算符. 用于访问 containers .
对于 C++ 程序员,cplusplus.com是你的 friend 。
关于C++:问题 vector STL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35332227/