0

I have a debug assertion that fails when running Dinner.Init(Baskets,Bags);

The error message is vector subscript out of range.

I think it has something to do with the initialization of the variable sized arrays. It takes an unusually long time at the step Dinner(int num): Apple(num){ }.

Are the error message and delay related? Is there a solution for both?

In foo.h

#include <vector>
extern int num1
extern int num2
#define Baskets = num1+num2
#define Bags = num1*2
struct  AppleStruct
{
    std::vector<int> Chunks;
    AppleStruct(){}
    AppleStruct(int num):Chunks(num){ }
};
Class Dinner
{
  std::vector<AppleStruct> Apple;
  public:
  Dinner(){}
  Dinner(int num): Apple(num){ }
  void Init(int num1, int num2);
}

void Dinner::Init(int num1, int num2)
{
int i, j;

    for (i=0; i<num1; i++)          // Fill everything INVALIDs
    {
        for (j=0; j<num2; j++)
        {
            Apple[i].Chunks[j]=1;
        }
    }
}

In foo.cpp

#include "foo.h"
int num1;
int num2;
int main(int argc, char *argv[])
{
    sscanf_s(argv[1],"%d",&num1);
    sscanf_s(argv[2],"%d",&num2);
    AppleStruct(Bags);
    Dinner(Baskets);
    Dinner.Init(Baskets,Bags);
    return 0;
}
2
  • Your code is not valid C++ and does not compile. Commented Nov 26, 2014 at 22:07
  • What's wrong with it? Commented Nov 26, 2014 at 22:08

2 Answers 2

0

In the for loop ,you are assigning values to the vector chunk but you have not allocated space for a structure to hold the chunk vector.

 for (i=0; i<num1; i++)          // Fill everything INVALIDs
{
    struct AppleStruct newstruct;
    for (j=0; j<num2; j++)
    {
        newstruct.Chunks.push_back(1);
    }
    Apple.push_back(newstruct);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! This takes a long time. Is it normal?
0

Vector is not a regular array, you should push_back to add element first. change:

Apple[i].Chunks[j] = 1; 

to

Apple[i].Chunks[j].push_back(1);

Also, you need add element to Apple too.

1 Comment

I tried this, but got an red line under Apple, and the error is std::vec<AppleStruct,std::allocator<AppleStruct>> Dinner::Apple, Error: expression must have class type. Why did this happen? Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.