简体   繁体   中英

What is the structure of a std::vector?

I have made a recursive way of printing all of the elements of a vector, but it returns nonsense! and it throws a really strange exception:

Exception thrown: read access violation.
std::vector<int,std::allocator<int> >::operator[](...) returned nullptr.

And it outputs: 12358000

This is the code. What is the mistake I have made?

#include <iostream>
#include <vector>
using namespace std;

int printVec(vector<int>* foo) {
    if ((*foo).empty())
        return 0;
    else {
        cout << (*foo)[0];
        printVec(foo + 4);
    }
}
int main() {
    vector<int> ref{ 1,2,3,4,5,6,7,8,9,0 };
    printVec(&ref);
}

foo is a pointer to a std::vector<int> .

foo + 4 is adding 4 lots of sizeof(std::vector<int>) to foo in pointer arithmetic. There is not a std::vector at that location, so the behaviour of printVec(foo + 4) is undefined.

The expression (*foo)[0] is calling the overloaded [] operator on a std::vector which access the first element in the vector. If there is no element at that position then the behaviour of the program is undefined.

What is the mistake I have made?

You are using a pointer to a single vector and treat it as if it points into an array of std::vector<int> . It is only allowed to increment pointers that point to elements in arrays (actually you are allowed to get a pointer one past an object, but not more). A single std::vector is not an array and your code invokes undefined behavior by incrementing foo here: printVec(foo + 4); .

If you want to "point to" elements of the vector use iterators:

#include <iostream>
#include <vector>
using namespace std;

template <typename IT>
void printVec(IT current, IT end) {
    if (current == end) return;
    else {
        cout << *current;
        printVec(current+1,end);
    }
}
int main() {
    vector<int> ref{ 1,2,3,4,5,6,7,8,9,0 };
    printVec(ref.begin(),ref.end());
}

What is the structure of a std::vector?

You need not know nor care. If you want to iterate elements use iterators. If you want to access the underlying array use .data() .

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