对于具有引用返回类型的搜索算法,默认返回值应该是什么?

For a search algo with reference return type, what should be the default return value?

本文关键字:返回值 默认 是什么 搜索算法 于具 引用 返回类型      更新时间:2023-10-16

假设我有一个数组,我想检索对该数组元素的引用。

struct A {
int n;
}
A& search_algo(A* AList, int len, int target) {
for (int i = 0; i < len; i++) {
if (AList[i].n == target) { return AList[i]; }
}
return what?   //problem comes here, target not in array, what should I return
}

我想知道处理它最传统的方法是什么,或者什么返回值最有意义。就像我怎样才能最好地传达"你的东西不在这里,走开"的信息。类似于nullptr的东西会很棒。

我当前的解决方案是初始化堆栈上A的对象并将其返回。虽然我可以很好地编译,但返回对局部变量的引用是不安全的。

我正在考虑使用new初始化堆上的对象,但这会很混乱,我将不得不处理内存释放。我不喜欢。

一个好的做法是返回找到元素的索引/位置,而不是返回找到的值。这就是STL所做的,它返回找到的元素的位置/迭代器,如果未找到该元素,则返回最后一个元素之前的位置 1 单位,这表明在容器中找不到该元素。如果在数组中找不到该元素,则可以返回len。例如

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct A {
int n;
};
int search_algo(A* AList, int len, int target) {
for (int i = 0; i < len; i++)
if (AList[i].n == target)
return i;
return len;
}
int main(){
int _len = 4;
A _list[_len] = {6,7,8,9};
int idx1 = search_algo(_list,_len,7);
int idx2 = search_algo(_list,_len,10);
if(idx1==_len)
cout<<"Element not found"<<endl;
else
cout<<"Element found at "<<idx1<<" index and it's value is "<<_list[idx1].n<<endl;
if(idx2==_len)
cout<<"Element not found"<<endl;
else
cout<<"Element found at "<<idx2<<" index and it's value is "<<_list[idx2].n<<endl;
}

输出:

Element found at 1 index and it's value is 7
Element not found

返回索引将是一个很好的做法。但如果你坚持参考,我想你可以在search_algo末尾抛出一个例外。

返回容器或len的 last(( 迭代器以指示 find(( 失败。这是STL的惯例,也是一种良好做法。

template<typename InputIterator, typename T>
InputIterator find (InputIterator first, InputIterator last, const T& val)
{
while (first!=last) {
if (*first==val) return first;
++first;
}
return last;
}

如果您期望"未找到"作为有效结果,则不应返回对找到对象的引用,因为C++中没有"null"引用。

您可以返回一个指针(nullptr 表示未找到(、一个迭代器(一个过去最后一个表示未找到(。

在标准库中,返回引用的函数通常不用于搜索元素,并且通常是没有要返回的元素的例外情况。所以它只会抛出一个异常,例如std::map::at()