返回值和类型的问题
int* myfind2(const vector<int>&vec, int value) {for (int ix = 0; ix <vec.size(); ++ix) {
if (vec == value)
return &vec;
return 0;
}
}
上述代码中,一直报返回类型和值不匹配的问题,请问哪里有问题,纯菜鸟,求助
因为你的代码里面有一个return 0,而你的返回类型应该是一个整型的指针,不是整型 #include <vector>
using std::vector;
const int *myfind2(const vector<int> &vec, int value) {
for(int ix = 0; ix < vec.size(); ++ix) {
if(vec == value)
return &vec;
return 0;
}
// return ???;
return 0;
}
试试这个:#include <iostream>
#include <vector>
using std::cout, std::endl, std::vector;
int* myfind2(const vector<int>& vec, int value) {
for (int x: vec) {
if (x == value) {
return &x;
}
}
return NULL;
}
int main() {
vector<int>arr = { 13, 2, 3, 4, 5 };
int x = 3;
int* p = myfind2(arr, x);
cout << *p;
return 0;
} 傻眼貓咪 发表于 2022-2-11 17:52
试试这个:
返回局部变量的地址?
$ cat main.cpp
#include <iostream>
#include <vector>
using std::cout, std::endl, std::vector;
int* myfind2(const vector<int>& vec, int value) {
for (int x: vec) {
if (x == value) {
return &x;
}
}
return NULL;
}
int main() {
vector<int>arr = { 13, 2, 3, 4, 5 };
int x = 3;
int* p = myfind2(arr, x);
cout << *p;
return 0;
}
$ g++-debug -o main main.cpp
main.cpp: In function ‘int* myfind2(const std::vector<int>&, int)’:
main.cpp:9:20: warning: address of local variable ‘x’ returned [-Wreturn-local-addr]
9 | return &x;
| ^~
main.cpp:7:14: note: declared here
7 | for (int x: vec) {
| ^
$ 人造人 发表于 2022-2-11 19:07
返回局部变量的地址?
抱歉,失误了{:10_282:}{:10_282:}{:10_282:}
#include <iostream>
#include <vector>
using std::cout, std::endl, std::vector;
int* myfind2(const vector<int>& vec, int value) {
int n = 0;
for (int x: vec) {
if (x == value) {
return (int*)&vec;
}
n++;
}
return NULL;
}
int main() {
vector<int>arr = { 13, 2, 3, 17, 5 };
int x = 3, y = 17;
int* p = myfind2(arr, x), *q = myfind2(arr, y);
cout << *p << endl;
cout << *q << endl;
return 0;
}
页:
[1]