user1056903 user1056903 - 20 days ago 4
C++ Question

Size of C++ vector is invalid

The following code is given:

#include <vector>
std::vector<int> intVec;
intVec[0] = 1;
std::cout << "intVec Size: " << intVec.size();

Why does
returns the invalid size 0? How can I fix that issue? I don't want to use
instead and also don't want to zero-initialize the vector with 5 elements.

Edit: The size of the vector should be 1 after
intVec[0] = 1


From your non-understable question, I can guess that you want the vector to treat the [] operator as "edit if it is exist or create if it is not". Some thing like the behavior of [] operator in std::map for example..

You simply can not. It was not designed like this.

BTW, you may do something like this: (It is bad idea. Do not.)

int& funky_operator(std::vector<int>& vec, const std::size_t index){
    return vec[index];
int main(){
    std::vector<int> intVec;
    funky_operator(intVec,0) = 1;
    std::cout << "intVec Size: " << intVec.size();

Again, this is stupid code. Do not use in real life. However, it is what you want.