C++serach的编程案例
时间: 2024-09-20 13:15:06 浏览: 33
在C++中,"search"通常指的是搜索或查找操作,这在许多场景下都非常常见,比如在数组、字符串、容器(如`std::vector`、`std::map`等)以及自定义数据结构中查找特定元素。以下是一些常见的搜索编程案例:
1. **数组搜索**:
```cpp
int arr[] = {1, 2, 3, 4, 5};
int target = 3;
bool found = false;
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
if (arr[i] == target) {
found = true;
break;
}
}
if (found) {
std::cout << "Element found at index: " << i << std::endl;
} else {
std::cout << "Element not found." << std::endl;
}
```
2. **动态数组(std::vector)搜索**:
```cpp
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "Element found at position: " << it - vec.begin() << std::endl;
} else {
std::cout << "Element not found in vector." << std::endl;
}
```
3. **线性搜索字符串(std::string)**:
```cpp
std::string str = "Hello World";
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::cout << "Substring found starting from position: " << pos << std::endl;
} else {
std::cout << "Substring not found in the string." << std::endl;
}
```
4. **使用STL算法(如std::count_if)**:
```cpp
std::vector<int> vec = {1, 1, 2, 2, 3, 3, 3};
int count = std::count(vec.begin(), vec.end(), 3);
std::cout << "Count of element 3: " << count << std::endl;
```
这些例子展示了如何在不同类型的容器中进行线性查找和使用内置函数进行复杂度更优的搜索。
阅读全文