简体   繁体   中英

Non-Constant Array

I'm trying to create an array using a class object, and the array size can vary. What I'm doing is creating a "Library" using C++ on Visual Studio 2015, and the information comes from a text file. The first line of the file holds the number of books, and I've got the program to read the first line and set that to an integer variable. I'm trying to get a constant integer to be set as the size equal to the previous integer, but when I try to create the array, it tell's me it's not a constant.

int numBooks;
    inputfile >> numBooks;

    const int SIZE = numBooks;
    Library records[SIZE]; //"Expression must have a constant value"

What do I need to do here to get this to work. The number of books will change, so must the size of the array.

Don't use a raw array. The size of a raw array must be known at compile time. Use std::vector instead:

int numBooks;
inputfile >> numBooks;
std::vector<Library> records(numBooks);

Chances are that you won't need to tell the vector an initial size. Just tell it to grow with each item:

int numBooks;
inputfile >> numBooks;
std::vector<Library> records;
// ...
records.push_back(book);

Also note that Library is a bad name for this class. It should probably be called Book instead.

const int SIZE = numBooks;

Must be initialized at compile time, hence you can't initialize it.

The best alternative is to use a std::vector :

size_t numBooks;
cin >> numBooks;
std::vector<Library> records(numBooks);

Note:

In contrary to what @Christian Hackl stated in their answer , in many cases (especially with user defined types) it is better to use something along these lines:

size_t numBooks;
cin >> numBooks;
std::vector<Library> records;
records.reserve(numBooks);

and add elements there with std::vector::emplace_back();

std::vector<Library> records(numBooks);

would call the default constructor for Library numBooks times and later you would come up manipulating the vector elements through copy operations or such.

std::vector::emplace_back() would allow to move newly constructed Library records directly to the vector, and std::vector::reserve() will guarantee that no memory reallocation needs to take place (which could become costly performance wise).

For a large number of records read from a file that would be definitely worth to consider.

The value of SIZE and so the size of the array is not initialized until the runtime, therefore which is not according to how C++ works.

You must assign a fixed, real integer value when initializing an array.

Use vector otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM