我在二维向量中是否正确分配了内存
Have I allocated memory correctly in 2d vector?
我尝试用常规事务(如付款(制作日历,并在1月31日添加事务时获得out_of_range
。所以我认为我在2d向量中错误地分配了一个内存。此外,我尝试了调试,但无法从向量的向量中检查向量(月(的大小。所以我也尝试了sizeof
,但他显示0在这种情况下为CCD_ 3,在这种情况中为1:CCD_。输入为:12 Add 5 Salary
Add 31 Walk
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void Add(vector<vector<string>>& business, const int current_month)
{
int current_day;
string s;
cout << "Enter a day, please" << endl;
cin >> current_day;
cout << "Enter your business, please" << endl;
cin >> s;
current_day -= 1;
business[current_month][current_day] = s;
}
int main()
{
int current_month = 0;
vector<int> count_of_days_in_months = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
vector<vector<string> > business(12, vector<string>(( count_of_days_in_months[current_month] ) - 1));
cout << sizeof(business) / sizeof(business[0][0]);
int Q;
cin >> Q;
string command;
for (int j = 0; j < Q; j++)
{
cout << "Enter a command, please" << endl;
cin >> command;
if (command == "Add")
Add(business, current_month);
else if (command == "Dump")
Dump(business, current_month);
else if (command == "Next")
Next(business, count_of_days_in_months, current_month);
}
}
std::vector
构造函数记忆起来总是令人困惑。正在调用此构造函数:
std::vector::vector(size_type n, const value_type& v)
其创建n个项目并将v复制到每个项目。结果是一个由12个项目组成的数组,每个项目的天数与当月相同。
看起来你想用这个表分配一整年的天数。我不知道std::vector
的构造函数能做到这一点。但手动操作并不需要太多代码:
std::vector<std::vector<string>> business;
business.reserve(count_of_days_in_months.size());
for (auto days : count_of_days_in_months) {
business.emplace_back(days);
}
演示:https://godbolt.org/z/Jd_94W
相关文章:
- 我在二维向量中是否正确分配了内存
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 是否可以使用其他变量为变量分配值,而无需在 C++ 中更改其值?
- 堆分配的对象是否存在永不为空的唯一所有者?
- 新分配指向函数的指针是否合法?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 是否可以使用分配器对象来释放另一个分配器分配的内存?
- 释放动态分配的内存时是否需要执行此额外步骤
- std::initializer_list 堆是否分配内存?
- 迭代器是否分配内存(如指针)?
- C 检查值是否分配给了类的成员
- 内存管理 - 添加小部件是否分配父级
- 一般来说,如何找出客户端是否分配了静态Ip或是dhcp客户端
- 未使用的 STL 容器是否分配内存
- 移动是否分配了 std::fstream 关闭原始流
- 我如何知道是否分配了内存插槽
- 要声明指针变量,内存是否分配给指针的名称或指针的地址?
- 宏是否分配内存?
- 是否有一种方法来判断是否分配了内存缓冲区并且必须删除