[英]What should happen when the return value from a C++ function that returns a reference of an undefined object type is not assigned?
[英]For a search algo with reference return type, what should be the default return value?
假设我有一个数组,我想检索对该数组元素的引用。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.