对于具有引用返回类型的搜索算法,默认返回值应该是什么?
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末尾抛出一个例外。
返回容器或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()
相关文章:
- 从python中调用C++函数并获取返回值
- 为什么模板类中的对象不能返回值
- 返回值优化:显式移动还是隐式
- lock_guard是否保护返回值
- 调用CreateProcess()并获取字符串的返回值
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 查找 GCD:并非所有控制路径都返回值
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 返回类型为 int 的函数中的默认返回值 1?
- 是否有C 函数的默认返回值
- 为什么C++未指定 return 语句时不默认构造返回值?
- 默认情况下是函数返回值常量(右值)
- 模板变量的默认返回值
- 递归中的默认返回值
- c++中布尔类型返回函数的默认返回值
- C'Tor 的 C++ 返回值 + 错误处理的默认返回值
- 使用函数返回值作为默认模板非类型形参
- 带有默认返回值的C++弱函子