说我有一个数组,我想检索对该数组元素的引用。
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的末尾抛出异常。
返回容器的last()迭代器,或返回len
以指示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 ++中没有“空”引用。
您可以返回一个指针(未找到为nullptr),一个迭代器(未找到为最后一个)。
在标准库中,返回引用的函数通常不用于搜索元素,并且在没有元素要返回的情况下通常是例外情况。因此它只会抛出一个异常,例如std::map::at()