Accessing vectors of structs

13,026

Solution 1

Don't create a pointer to a vector. Just do

vector<OutputStore> OutputFileData(100);

And you'll be fine. To make your code above work you'll need to do the following

(*OutputFileData)[5].myINT = 27;

Solution 2

Because when you apply the [] operator on a pointer, it will index into that pointer, not that object. To get to the object you first need to dereference your vector pointer.

(*OutputFileData)[5].myINT = 27;
//*OutputFileData is the same as OutputFileData[0]

If you want to use the [] operator directly on the vector don't declare it as a pointer.

vector<OutputStore> OutputFileData(100);
OutputFileData[5].myINT = 27;

A vector is just a class like any other in C++. If you create a pointer to it, you are not working directly with the object until you dereference it.

Share:
13,026
Columbo
Author by

Columbo

Updated on June 04, 2022

Comments

  • Columbo
    Columbo almost 2 years

    I have a struct:

    struct OutputStore 
    {
        int myINT;
        string mySTRING;
    }
    

    If I create an array of type OutputStore as follows:

    OutputStore *OutputFileData = new OutputStore[100];
    

    then I can address it with:

    OutputFileData[5].myINT = 27;
    

    But if I use a vector instead of an array:

    vector<OutputStore> *OutputFileData = new vector<OutputStore>(100);
    

    Then I get an '... is not a member of 'std::vector<_Ty>' error if I try:

    OutputFileData[5].myINT = 27;
    

    Since you can access a vector via it's index just as you can an array, why does this line not work. I'm just interested to know as it suggests I'm missing some fundamental bit of understanding.

    (I changed to a vector as I wanted to push_back as I do not know the size that my data will reach. I've got it to work by using a constructor for the structure and pushing back via that...I just want to understand what is going on here)

  • Columbo
    Columbo almost 15 years
    Thanks very much, I understand now.