Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if array index exists

Tags:

c++

arrays

Is there any way to check if a given index of an array exists? I am trying to set numerical index but something like 1, 5, 6,10. And so I want to see if these indexes already exist and if they do just increase another counter.

I normally work with php but I am trying to do this in c++, so basically I am trying to ask if there is an isset() way to use with c++

PS: Would this be easier with vectors? If so, can anyone point me to a good vector tutorial? Thanks

like image 995
AntonioCS Avatar asked Dec 10 '22 22:12

AntonioCS


1 Answers

In C++, the size of an array is fixed when it is declared, and while you can access off the end of the declared array size, this is very dangerous and the source of hard-to-track-down bugs:

int i[10];
i[10] = 2; // Legal but very dangerous! Writing on memory you don't know about

It seems that you want array-like behavior, but without all elements being filled. Traditionally, this is in the realms of hash-tables. Vectors are not such a good solution here as you will have empty elements taking up space, much better is something like a map, where you can test if an element exists by searching for it and interpreting the result:

#include <map>
#include <string>

// Declare the map - integer keys, string values    
std::map<int, std::string> a;

// Add an item at an arbitrary location
a[2] = std::string("A string");

// Find a key that isn't present
if(a.find(1) == a.end())
{
   // This code will be run in this example
   std::cout << "Not found" << std::endl;
}
else
{
   std::cout << "Found" << std::endl;
}

One word of warning: Use the above method to find if a key exists, rather than something like testing for a default value

if(a[2] == 0)
{
    a[2] = myValueToPutIn;
}

as the behavior of a map is to insert a default constructed object on the first access of that key value, if nothing is currently present.

like image 168
user23167 Avatar answered Dec 31 '22 13:12

user23167