Search code examples
c++vectordeclarationoutofrangeexception

Have I allocated memory correctly in 2d vector?


I tried to do a calendar with regular affairs(like payment) and get out_of_range when added an affair to 31 January. So I think that I allocated a memory incorrectly in my 2d vector. Also, I tried debugging, but I couldn't check the size of the vector(month) from the vector of vectors. So I also tried a sizeof but he shows 0 in this case: cout << sizeof(business) / sizeof(business[0][0]); and 1 in this: cout << sizeof(business) / sizeof(business[0]);. Input is: 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);
    }

}

Solution

  • The std::vector constructors are endlessly confusing to memorize. This constructor is getting called:

    std::vector::vector(size_type n, const value_type& v)
    

    which create n items and copies v to each one. The result is an array of 12 items, each with the same number of days as the current month.

    It looks like you want to allocate a whole year's worth of days using that table. I don't know a constructor for std::vector that does that. But it's not a lot of code to do it manually:

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

    Demo: https://godbolt.org/z/Jd_94W