首页 > 解决方案 > 我用[]方法赋值,通过std::cout可以打印出数据,但是为什么size()返回0呢?

问题描述

我用reserve函数预分配10个双倍内存,然后用operator[]方法赋值,可以通过std::cout打印出数据,但是为什么size()是0呢?

(注意:有几种解决方案,但我想知道为什么会发生这种情况?)

代码在这里

#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;
}

出处如下:

0 12 24 36 48 60 72 84 96 108

大小为:0

容量为:10

标签: c++stdvector

解决方案


推荐阅读