0

I have found myself repeatedly writing the following function :

// This function will try to find the 'item' in 'array'.
// If successful, it will return 'true' and set the 'index' appropriately.
// Otherwise it will return false.
bool CanFindItem(data_type item, const data_type* array, int array_size, int& index) const
{
    bool found = false;
    index=0;
    while(!found && i < array_size)
    {
         if (array[index] == item)
              found = true;
         else index++;             
    }

    return found;
}

Usually I write a similar function for each class/struct etc. need it.

My question is, is there a way to have this snippet ready to use without rewriting it ? I am programming in VS 2010.

Wartin
  • 1,965
  • 5
  • 25
  • 40

3 Answers3

1

You can turn it into a template by moving it to the .h file and putting template<typename data_type> at the front of the function.

You could also switch to using standard C++ features such as the std::find algorithm.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

Even in MFC you can use modern (ie post 1995) c++ and STL constructs

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
  • @wartim - sorry that was a bit mean! But before you waste time writing all these functions do look at an STL tutorial. It's complicated to begin with but it will save you years of wasted work in the long run – Martin Beckett Apr 04 '12 at 15:07
0

You can use std::find ... There's an example using an array in the link.

(std::find (array,array + array_size, item) != array + array_size);
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185