How to access the contents of a vector from a pointer to the vector in C++?

后端 未结 8 893
不思量自难忘°
不思量自难忘° 2020-11-30 17:26

I have a pointer to a vector. Now, how can I read the contents of the vector through pointer?

8条回答
  •  萌比男神i
    2020-11-30 17:56

    Access it like any other pointer value:

    std::vector* v = new std::vector();
    
    v->push_back(0);
    v->push_back(12);
    v->push_back(1);
    
    int twelve = v->at(1);
    int one = (*v)[2];
    
    // iterate it
    for(std::vector::const_iterator cit = v->begin(), e = v->end; 
        cit != e;  ++cit)
    {
        int value = *cit;
    }
    
    // or, more perversely
    for(int x = 0; x < v->size(); ++x)
    {
        int value = (*v)[x];
    }
    
    // Or -- with C++ 11 support
    for(auto i : *v)
    {
       int value = i;
    }
    

提交回复
热议问题