Lets say I have an object array declared like this:
Object Array[100];
int count = 0;
bool exit;
do
{
if (Array[count] == "")
{
//code that stores data
exit = true;
}
else
{
count++;
}
}
while (exit != true);
I keep having errors from the compiler which says:
error: no match for ‘operator==’ in ‘Array[count] == ""'
I know I can use a for loop function to store them correctly or even use a vector, but for now, I have to use this method to check if the array is empty/null. Any idea how to do it? I have seen many examples here, but almost all of it are string/int/float etc etc arrays.
When you created the array using: Object Array[100];
it already created 100 memory slots for your Object
s, and called the default constructor for each one of them.
Physically, there are 100 elements in your array right after the quoted line.
Logically, there are as much as you decide, and its best you save that number to count
.
If the Object
's default c'tor is not enough in terms of initialization, then you have several options for checking weather it's content is initialized or not:
bool isInitialized()
) operator==
that takes const char *
as an argument and compare it to ""
. operator==
that takes another Object
as an argument and compare it to ""
assuming Object
has a c'tor from const char *
. The array itself cannot be "empty".
Object Array[100];
is a declaration that creates an array of 100 Object
s. They are already constructed and present (if default constructible).
If the type Object
has some notion of an "empty" state you could check for that (A std::vector
for example provides the member .empty()
to check for emptyness.) or you can use a container to hold your data (which also makes it part of the heap instead of the stack memory and enables dynamic resizing).
std::vector<Object> vec;
int count = 0;
// do stuff...
do
{
if (count >= vec.size())
{
//code that stores data
exit = true;
}
else
{
count++;
}
}
while (exit != true);
Whereas you could also say std::size_t count = vec.size();
.
Object Array[100];
cannot be empty. On the other hand, pointer to dynamically allocated array can be initialized to nullptr and checked against that:
Object *Array = nullptr;
if(!Array) // or Array == nullptr
cout << "Array is empty (unallocated)" << endl;
Array = new Array[100];
if(Array) // or Array != nullptr
cout << "Array is NOT empty" << endl;
Array[count]
doesn't make sense. you are accessing element at index count
(which is a bad name for index) and comparing that with const char*
. std::vector
is the way to go. Code above (and everything other than using std::vector
) - ugly and bad practice.
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.