对于普通数组 find(开始位置,结束位置+1,要查找元素)返回所查找元素的地址,如果需要知道元素的下标,还需减去数组首地址。 如果找到元素,上述表示法得到的是元素在数组中第一次出现的下标;如果找不到元素,上述表示法得到的就是数组最后一个元素的下标 +1。可以利用这一点判断数组中是否含有某个元素。 #include<bits/stdc++.h> using namespace std; int main(){ int a[5]={1,5,2,4,3}; int x=4; int y=9; cout<<(find(a,a+5,x)-a)<<endl; cout<<(find(a,a+5,y)-a)<<endl; return 0; } 对于字符串 find函数返回值:若找到,返回第一次出现的位置的下标;否则返回 -1 #include<bits/stdc++.h> using namespace std; int main(){ string str1="abcdefghi", str2="cde"; char c='m'; int f1=str1.find(str2); cout<<f1<<endl;//从串str1中查找时str2,返回str2中首个字符在str1中的下标 if(f1==-1) cout<<"No"<<endl; else cout<<"Yes"<<endl; int f2=str1.find(str2,2); cout<<f2<<endl;//从str1的第2个字符开始查找str2 if(f2==-1) cout<<"No"<<endl; else cout<<"Yes"<<endl; int f3=str1.find(c); cout<<f3<<endl;//在str1中查找字符e if(f3==-1) cout<<"No"<<endl; else cout<<"Yes"<<endl; return 0; }