why vector? why not std::array? |
A
std::array size must be known at compile time, so it has the same disadvantage as a regular array. Lines 8-9 declare a Variable Length Array, something the C++ standard doesn't allow. (compiler language extensions aren't portable)
It can't be sized or resized at run-time, as the OP's code snippet SEEMS to want to do (line 18).
I've been trying to initialize a basic array with the limit being 5 and set size equal to 5 and put that in the array. |
The problem(s) boil down to line 8 doesn't declare data member
size as a
static const, and line 18 appears to ask the user for a size for the array instead of asking for data for an array of size 5.
Where is the ctor's definition that was declared on line 12?
The name of an array resolves to a pointer to the first element of the pointer. Lines 19 and 23 can't compare a int* to an int.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
class CheckedArray
{
private:
static const int size = 5;
int arr[size];
public:
// CheckedArray(); // no ctor definition
void info();
};
int main()
{
CheckedArray enter;
enter.info();
}
void CheckedArray::info()
{
// this statement is misleading
std::cout << "Enter in size of an array no more than 5:\n";
// this is filling the array with data,
// not asking for some information about the array's size
for (int i = 0; i < size; i++)
{
std::cin >> arr[i];
}
// maybe this is what you intend?
std::cout << "The size is: " << size << '\n';
}
|
To use a
std::array still requires the size data member to be declared as static const.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <array>
class CheckedArray
{
private:
static const int size = 5;
std::array<int, size> arr;
public:
// CheckedArray(); // no ctor definition
void info();
};
int main()
{
CheckedArray enter;
enter.info();
}
void CheckedArray::info()
{
// this statement is misleading
std::cout << "Enter in size of an array no more than 5:\n";
// this is filling the array with data,
// not asking for some information about the array's size
for (int i = 0; i < size; i++)
{
std::cin >> arr[i];
}
// maybe this is what you intend?
std::cout << "The size is: " << size << '\n';
}
|
Using a
std::vector makes it easy to resize at run-time the container's size, if that is something the OP wants. A std::vector can be declared with a data member that isn't declared
static const,
OR declare the
size data member as static const.
No need for the "extra"
size data member with
std::vector or
std::array they know their size already.