lamborghini 123
lamborghini 123

Reputation: 49

First occurrence of element in an array using pointers (C++)

int findFirst(const string a[], int n, string target)
 {
 for (int i = 0; i < n; i++)
 if (a[i] == target)
 return i;
return -1;
} 

How do I write the above program without using square brackets and using the following function header?

int findFirst(const string* a, int n, string target)

Upvotes: 0

Views: 545

Answers (2)

Igor
Igor

Reputation: 515

First of all, if you write a function that have a pointer as an input parameter it would be better to check this pointer on nullptr (or 0):

int findFirst(const string * a, int n, string target)
{
  if (a)
  {
    // do search
  }
  return -1;
}

Second, for searching the item position you can use algorithms from Standard Library:

#include <algorithm>

int findFirst(const std::string* a, int n, std::string target)
{
    if (a)
    {
        int res = std::distance(a, std::find(a, a + n, target));
        if (res < n)
        {
            return res;
        }
    }
    return -1;
}

Third, it would be better to pass the target by const reference to exclude unnecessary call of copy constructor. And as a result we can have the following final solution:

#include <algorithm>

int findFirst(const std::string* a, int n, const std::string& target)
{
    if (a)
    {
        int res = std::distance(a, std::find(a, a + n, target));
        if (res < n)
        {
            return res;
        }
    }
    return -1;
}

Upvotes: 0

molbdnilo
molbdnilo

Reputation: 66371

You can simply replace the function header; const string a[] already is a pointer parameter and means exactly the same as const string* a.

Then, you can either dereference a + i

for (int i = 0; i < n; i++)
    if (*(a + i) == target)

or increment a along with i

for (int i = 0; i < n; i++, a++)
    if (*a == target)

or you could use only pointers

for (const string* p = a; p < a + n; p++)
    if (*p == target)

Upvotes: 1

Related Questions