Reputation: 1281
I did getting divisors by calling functions named getDivisors
and return their values formatted by container vector<int>
.
Since I am a new to C++
container, I tried to print my divisor integers by for loops using an iterator. However, in my opinions, it seems too complex.
Is there any easy way to show stored integers in vector STL
?
And I don't get it why the iterator variable it is pointer type? Could you explain it more about it? I was confused that the compilers show the error message when I did
itnot
it`
Below are my simple codes.
#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;
}
Upvotes: 0
Views: 112
Reputation: 1940
Iterators are convenient abstractions which help in accessing a container. They are not pointers.
One of the things you've got to be careful about, is that an iterator can get invalidated if the container associated with it changes substantially
Get a good book on STL and get the fundamentals right before proceeding. Here's a primer but it can only do so much.
http://www.cprogramming.com/tutorial/stl/iterators.html
Upvotes: 0
Reputation: 41057
You haven't mentioned which compiler you are using, but in C++11 conforming compilers you can use auto and the 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
A pointer is a kind of iterator specifically a random access iterator. Iterators are designed as abstractions of pointers with operators like *
, ->
, ++
, --
, etc. for accessing containers.
For C++ programmers, cplusplus.com is your friend.
Upvotes: 5
Reputation: 327
It is not a pointer, it's an iterator. It overrides operator *
to provide pointer-like behavior. You can read more about C++ STL to understand that.
If you are using C++11 or later, use this:
for (auto x : divisors) cout << x << endl;
Upvotes: 2