使用指针(C )在数组中首次出现元素

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

本文关键字:元素 数组 指针      更新时间:2023-10-16
int findFirst(const string a[], int n, string target)
 {
 for (int i = 0; i < n; i++)
 if (a[i] == target)
 return i;
return -1;
} 

如何在不使用方括号并使用以下功能标头的情况下编写上述程序?

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

您可以简单地替换功能标头;const string a[]已经是一个指针参数,含义与const string* a完全相同。

然后,您可以解除a + i

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

或增量a以及i

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

,或者您只能使用指针

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

首先,如果您编写具有指针作为输入参数的函数,最好在Nullptr上检查此指针(或0):

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

第二,对于搜索项目位置,您可以使用标准库中的算法:

#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;
}

第三,最好通过cont引用传递目标,以排除不必要的复制构造函数。因此,我们可以拥有以下最终解决方案:

#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;
}