简体   繁体   中英

Accessing pointers of vector elements

I have this struct:

struct povezava{
    int p;
    int q;
    int cena;
    int index;
};

and this vector that contains pointers to the struct

vector<povezava*> povezave;

and I have to read information from a text file and then appoint the values to the elements of the vector

while(graf >> p1 >> q1 >> cena1){

        povezave[counter]->p=p1;
        povezave[counter]->q=q1;
        counter++;

    }

But there is an error when I try to access these elements, I'm guessing because they are not defined yet? The task says I have to use static data structures but that's impossible since the size of the array is dependant on a number in the graph. Is my only option to use dynamic allocation?(I really don't want to).

But there is an error when I try to access these elements, I'm guessing because they are not defined yet?

That's right. You need to create the elements. Fortunately, that's really easy, and should be demonstrated early on in your C++ book.

while(graf >> p1 >> q1 >> cena1){
    povezava newElement;
    newElement.p = p1;
    newElement.q = q1;

    povezave.push_back(newElement);
}

In this example I've also assumed that the vector is changed to std::vector<povezava> , because you've given no reason for it not to be.

You should go further and change its really confusing name.

Is my only option to use dynamic allocation?(I really don't want to).

Well, you already are (or, at least, you would be). A vector dynamically allocates its elements.

The task says I have to use static data structures but that's impossible since the size of the array is dependant on a number in the graph.

Depending on what this vague requirement means, it's possible that you cannot use a vector.

If you don't allocate the memory for the elements of the vector , you can't use them (set member of the elements, ...).

But the best solution is to have statically allocated variable inside the vector :

vector<povezava> povezave;

Of course, it means that you have to change the -> to . because the member aren't pointer anymore.

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