C++中如何实现查找功能
时间: 2023-11-27 08:53:08 浏览: 30
在C++中实现查找功能通常会用到STL中的容器,如vector、map、set等。具体实现方式取决于要查找的数据类型和查找的方式。
1. 在vector中查找
可以使用STL中的find函数,在vector中查找指定元素,示例代码如下:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec{1, 2, 3, 4, 5};
auto it = find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
cout << "Found " << *it << endl;
}
else {
cout << "Not found" << endl;
}
return 0;
}
```
2. 在map中查找
可以使用STL中的find函数,在map中查找指定键值对,示例代码如下:
```c++
#include <iostream>
#include <map>
using namespace std;
int main() {
map<string, int> m{{"apple", 1}, {"banana", 2}, {"orange", 3}};
auto it = m.find("banana");
if (it != m.end()) {
cout << "Found " << it->second << endl;
}
else {
cout << "Not found" << endl;
}
return 0;
}
```
3. 在set中查找
可以使用STL中的find函数,在set中查找指定元素,示例代码如下:
```c++
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s{1, 2, 3, 4, 5};
auto it = s.find(3);
if (it != s.end()) {
cout << "Found " << *it << endl;
}
else {
cout << "Not found" << endl;
}
return 0;
}
```
以上是三种常见的查找方式,需要注意的是,在使用STL中的find函数时,如果找到了指定元素,则返回指向该元素的迭代器;否则返回容器的end迭代器。