我在二维向量中是否正确分配了内存

Have I allocated memory correctly in 2d vector?

本文关键字:是否 分配 内存 向量 二维      更新时间:2023-10-16

我尝试用常规事务(如付款(制作日历,并在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