C++ 在伪代码中返回-1意味着什么

C++ 在伪代码中返回-1意味着什么,c++,pseudocode,C++,Pseudocode,我有以下伪代码,这是一个顺序搜索伪代码,我试图理解return-1的意思。我们为什么要回来?请有人解释一下 A[n] <-- K i <-- 0 while A[i] != K do i = i + 1 if(i<n) return i; else return -1; //What is this mean ? [n] 返回- 1是一种传递代码的方式,在没有返回中间的情况下,代码达到了结束。在本例中返回-1意味着数组中不存在元素K

我有以下伪代码,这是一个顺序搜索伪代码,我试图理解return-1的意思。我们为什么要回来?请有人解释一下

A[n] <-- K
i <-- 0
while A[i] != K do
     i = i + 1
if(i<n)
     return i;
else
     return -1;       //What is this mean ?

<代码> [n] 返回- 1是一种传递代码的方式,在没有返回中间的情况下,代码达到了结束。在本例中返回-1意味着数组中不存在元素K


请注意,返回0不用于此目的,因为它可能意味着元素存在于第0个索引中。如果你的函数在中间某个点可以返回- 1,则会选择一些其他的返回值来指示失败。

返回-1是一种传递代码的方法,在没有返回中间的情况下代码达到了结束。在本例中返回-1意味着数组中不存在元素K


请注意,返回0不用于此目的,因为它可能意味着元素存在于第0个索引中。如果您的函数是可以返回的-在中间某个点的1,则会选择其他返回值来指示失败。

如果您要搜索一个元素的序列,并返回该元素的索引,则需要某种方式来显示元素未被找到。负值在许多语言中都是无效的索引,因此返回
-1
只能意味着由于某种原因找不到元素

int index_of(const int *array, int sz, int elem) {
    for (int i = 0; i < sz; ++i) {
        if (array[i] == elem) { // found the element
            return i; // return the index of the element
        }
    }
    return -1; // couldn't find it
}
int索引_of(常量int*数组、int sz、int元素){
对于(int i=0;i
然后在调用代码中,您可能会

int calling() {
    int array[N];
    // populate array with data ...
    int idx = index_of(array, N, 4); // find where 4 is in the array
    if (idx < 0) {
        // 4 isn't in the array
    } else {
        // 4 IS in the array !
    }
}
int调用(){
整数数组[N];
//用数据填充数组。。。
int idx=index_of(array,N,4);//查找数组中4的位置
if(idx<0){
//4不在数组中
}否则{
//4在数组中!
}
}

如果要在序列中搜索元素,并返回该元素的索引,则需要某种方式来显示未找到该元素。负值在许多语言中都是无效的索引,因此返回
-1
只能意味着由于某种原因找不到元素

int index_of(const int *array, int sz, int elem) {
    for (int i = 0; i < sz; ++i) {
        if (array[i] == elem) { // found the element
            return i; // return the index of the element
        }
    }
    return -1; // couldn't find it
}
int索引_of(常量int*数组、int sz、int元素){
对于(int i=0;i
然后在调用代码中,您可能会

int calling() {
    int array[N];
    // populate array with data ...
    int idx = index_of(array, N, 4); // find where 4 is in the array
    if (idx < 0) {
        // 4 isn't in the array
    } else {
        // 4 IS in the array !
    }
}
int调用(){
整数数组[N];
//用数据填充数组。。。
int idx=index_of(array,N,4);//查找数组中4的位置
if(idx<0){
//4不在数组中
}否则{
//4在数组中!
}
}

这段代码结构奇特。通常情况下,为了避免出现多个
return
语句,它是这样弯曲的,但是有两个语句。对于这段代码,这意味着在第n个索引之前的数组A中没有等于K的元素。n可能是数组的大小,因此这减少为:这意味着数组A不包含任何等于K的元素。这段代码的结构很奇怪。通常情况下,为了避免出现多个
return
语句,它是这样弯曲的,但是有两个语句。对于这段代码,这意味着在第n个索引之前的数组A中没有等于K的元素。n可能是数组的大小,因此它减少为:这意味着数组A不包含任何等于K的元素。