0

I use the reserve function to pre-allocate 10 double-sized memory, and then use the operator[] method to assign values, and the data can be printed out through std::cout, but why does size() is 0?

(Note: There are several solutions, but I want to know why this happens?)

The code is here:

#include <iostream>
#include <vector>

int main(int argc, char* argv[]) {
    std::vector<double> test;
    test.reserve(10);
    for (int i = 0; i < 10; ++i) {
        test[i] = i * 12;
    }

    for (int i = 0; i < 10; ++i) {
        std::cout << test[i] << std::endl;
    }

    std::cout << "the size is: " << test.size() << std::endl;
    std::cout << "the capacity is: " << test.capacity() << std::endl;

    return 0;
}

The out is below:

0 12 24 36 48 60 72 84 96 108

the size is: 0

the capacity is: 10

  • 1
    `reserve` and `resize` are not the same thing. – Stephen Newell Sep 30 '20 at 02:38
  • `test[i] = i * 12;` is putting values into places that have not been added to the vector yet. – Eljay Sep 30 '20 at 02:42
  • As per [cppreference](https://en.cppreference.com/w/cpp/container/vector/reserve), `reserve` does not change the size of vector. – pvc Sep 30 '20 at 02:52
  • `test[i] = i * 12;` is putting values into places that have not been added to the vector yet. So where is test[i] stored in memory?@Eljay – yunfei liu Sep 30 '20 at 02:58
  • `reserve` allocates memory for the elements, but they're not valid until you resize the vector. What you're doing is pure undefined behavior. – Mark Ransom Sep 30 '20 at 03:02
  • Thanks. Why I use push_back everything is normal and it is a defined behavior? What is the difference between operator[] and push_back() assignment method?@Mark Ransom – yunfei liu Sep 30 '20 at 03:09
  • `push_back()` changes the size of the container, `operator[]` doesn't... – Blastfurnace Sep 30 '20 at 03:11
  • In the `operator[]` method of C++ STL, the pointer `_M_impl._M_finish` is not changed, so it does not know how many elements are in the container. – yunfei liu Sep 30 '20 at 07:26
  • It can be use [in this way](https://stackoverflow.com/a/13029463/14286060). – yunfei liu Sep 30 '20 at 07:32
  • Tips: Notice the difference between adds, modify and access. The operator[]() can access or modify elements, but **can't adds elements**. – yunfei liu Sep 30 '20 at 07:38

0 Answers0