简体   繁体   中英

C++:questions vector STL

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 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 not 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;
}

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 an int

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.

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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