1

I'm not very expert in programming with c++ so my question may appear a bit stupid, but I can't understand what I'm doing wrong.

I want to allocate a vector with the instruction

vector <short int> myvec(rowotot * coltot)

in order to represent a matrix.

Before proceeding, I want to verify if I have sufficient space to allocate my vector. If I use

try { 
    vector <short int> myvec(rowtot * coltot);
}
catch (bad_alloc& ba) {
    cert << "ERROR: ";
    cerr << ba.what() << endl;
}

and then I try to modify the elements of the vector, I can't because

myvec is not declared in this scope

How can I do the check on the memory before saving any value in the vector? I hope my question is clear.

Striezel
  • 3,693
  • 7
  • 23
  • 37
Cate
  • 11
  • 1
  • 4
  • 1
    Just do everything you need to do in the `try` block. Note: I've seen this question before. I'm looking for duplicates. – juanchopanza Jan 22 '16 at 15:47

1 Answers1

9

A simple solution is to declare the vector outside to the try block and then use std::vector::reserve to allocate the space in a try-catch block.

std::vector<short int> myvec;
try
{
    myvec.reserve(rowotot*coltot);
}
catch (const bad_alloc& ba) 
{
    cerr <<"ERROR: ";
    cerr << ba.what() << endl;
}

This puts the vector in the outer scope but allows the allocation to be catch-able.

If you need to have the vector with rowotot*coltot elements already in it then you could use the same thing but either call std::vector::resize to create the items or create a temporary vector and assign it to myvec.

std::vector<short int> myvec;
try
{
    myvec.resize(rowotot*coltot);
    // or
    myvec = std::vector<short int>(rowotot*coltot);
}
catch (const bad_alloc& ba) 
{
    cerr <<"ERROR: ";
    cerr << ba.what() << endl;
}

I also change catch (bad_alloc& ba) to catch (const bad_alloc& ba) as it is preferred to catch by const &

Chirag Jain
  • 143
  • 2
  • 8
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    Or maybe reassign it in the try block, like: `myvec = std::vector(rowotot*coltot)`, so that it already contains the items. Otherwise you rely on the assumption that outside the try block not more than `rowotot*coltot` items will be added and it won't need to reallocate. – tmlen Jan 22 '16 at 15:55