c++ - 我用[]方法赋值,通过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# - 如何在 selenium c# 中隐藏 firefox 浏览器
- c# - 当我想选择gridview的当前行时遇到问题
- html - 如何在 4 个网格列的第 2 列之后留出空间?
- javascript - 通过json数组字典翻译变量文本
- html - 为什么页脚的内容不相邻
- java - StringIndexOutOfBoundsException 任何人都可以吗?
- php - 更改 WooCommerce 结帐国家/地区字段默认选项显示标签
- javascript - 如何在 Vuejs 的上下文中使用 Vue 组件中的 JavaScript 文件
- mysql - 我想只为我登录的用户获取记录。目前我可以获取所有用户的记录。请调查这个问题
- mysql - Magento 2.3.6 分层导航选择异常错误