简体   繁体   中英

How to access individual elements from a 2d vector type pointer in c++

template<class T>
struct Edges{
    T u,v;
    int w;
};
int main(int argc, char const *argv[]){
    vector<struct Edges<int>> *ptr = new vector<struct Edges<int>>(
        {{1,2,1},{1,3,1}, {2,3,1}}
    );
    
    // access individual elements from the 2d pointer

    return 0;
}

How to access the individual elements from the ptr pointer? I tried to access it using ptr[0]->u but it shows compile time error base operand of '->' has non-pointer type 'std::vector<Edges<int> >'

You have a pointer to a single std::vector object, not an array of std::vector s. You are treating that pointer as if it were pointing at an array, which it is not (well, technically, any object can be treated as an array of 1 element).

ptr[0] is the same as *(ptr+0) ie *ptr , thus dereferencing that pointer will access the std::vector itself, not its 1st element. If you were to try using a higher index, ie ptr[1] , then you would access beyond that single std::vector , which is undefined behavior .

std::vector does not have an -> operator, which is why ptr[0]-> fails to compile.

But, even if you were accessing the std::vector 's 1st element correctly, -> would still be wrong to use, since the std::vector is not holding Edge* pointers for its elements. It is holding actual Edge objects, so you would need to use the . operator instead to access fields of each Edge .

You would need to use the following syntax instead to access individual fields of each Edge in the std::vector via the pointer:

(*ptr)[element_index].field

For example:

int main(){
    vector<Edges<int>> *ptr = new vector<Edges<int>>(
        {{1,2,1},{1,3,1}, {2,3,1}}
    );
    
    // access individual elements from the vector
    for (size_t i = 0; i < ptr->size(); ++i)
        cout << (*ptr)[i].u << ' ';

    delete ptr;
    return 0;
}

Online Demo

But, why are you using new like this at all? std::vector holds a dynamically allocated array, so there is no need to create the std::vector itself dynamically as well. It is unusual to new any standard C++ container. For example:

int main(){
    vector<Edges<int>> vec(
        {{1,2,1},{1,3,1}, {2,3,1}}
    );
    
    // access individual elements from the vector, eg
    for (size_t i = 0; i < vec.size(); ++i)
        cout << vec[i].u << ' ';

    return 0;
}

Online Demo

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