C++ 使用指针(C+;+;)在数组中首次出现元素
您可以简单地替换函数头C++ 使用指针(C+;+;)在数组中首次出现元素,c++,pointers,C++,Pointers,您可以简单地替换函数头const string a[]已经是指针参数,其含义与const string*a完全相同 然后,您可以取消引用a+i int findFirst(const string* a, int n, string target) 或者你只能使用指针 for (int i = 0; i < n; i++, a++) if (*a == target) for(常量字符串*p=a;p
const string a[]
已经是指针参数,其含义与const string*a
完全相同
然后,您可以取消引用a+i
int findFirst(const string* a, int n, string target)
或者你只能使用指针
for (int i = 0; i < n; i++, a++)
if (*a == target)
for(常量字符串*p=a;p
首先,如果您编写的函数有一个指针作为输入参数,最好在nullptr(或0)上检查该指针:
其次,要搜索项目位置,可以使用标准库中的算法:
int findFirst(const string * a, int n, string target)
{
if (a)
{
// do search
}
return -1;
}
#包括
int findFirst(常量std::string*a,int n,std::string目标)
{
如果(a)
{
int res=std::distance(a,std::find(a,a+n,target));
如果(res
第三,最好通过const引用传递目标,以排除不必要的复制构造函数调用。因此,我们可以得到以下最终解决方案:
#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;
}
#包括
int findFirst(常量std::string*a、int n、常量std::string和target)
{
如果(a)
{
int res=std::distance(a,std::find(a,a+n,target));
如果(res
您可以使用(*a==target)访问位于的元素。然后,您可以使用指针算法来增加a。a++将自动指向下一个字符。
for (const string* p = a; p < a + n; p++)
if (*p == target)
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;
}
#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;
}