tags:

views:

6612

answers:

4

Hey!

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

+3  A: 

My personal vote is for using a vector. They will resize dynamically, and as long as you don't do something stupid (like try and access an element that doesn't exist) they are quite friendly to use.

As for tutorials the best thing I could point you towards is a google search

mdec
A: 

Right right I forgot I had to create a fixed size. :(

AntonioCS
+6  A: 

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.

Thanks :) I'll read up on the map class and try it outThanks again!
AntonioCS
You can also use map.at() instead of [], which throws an exception if the element doesn't exist.
coppro
A: 

It sounds to me as though really a map is closest to what you want. You can use the Map class in the STL (standard template library)(http://www.cppreference.com/wiki/stl/map/start).

Maps provide a container for objects which can be referenced by a key (your "index").

Steve