std::vector 查找元素
时间: 2023-06-05 08:04:57 浏览: 317
您好!关于您的问题,我可以回答。std::vector查找元素可以使用STL的find函数,也可以通过遍历vector来查找。使用find函数的示例代码如下:
```c++
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "Found element: " << *it << std::endl;
} else {
std::cout << "Element not found!" << std::endl;
}
return 0;
}
```
以上是使用STL函数查找元素的代码示例。希望能对您有所帮助!
相关问题
std::vector如何查找
在std::vector中查找元素可以使用std::find或者std::find_if函数。其中,std::find函数可以直接查找指定元素,而std::find_if函数可以通过自定义的谓词函数来查找符合条件的元素。具体使用方法可以参考以下代码示例:
```
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct stMyTest {
int nID;
int nData;
stMyTest(int id, int data) :nID(id), nData(data) {}
};
struct stFindID {
int nFindID;
stFindID(int findID) :nFindID(findID) {}
bool operator()(const stMyTest&t1) {
return t1.nID == nFindID;
}
};
int main() {
vector<stMyTest> v;
for (int i = 0; i < 100; ++i) {
v.emplace_back(i, i + 1);
}
// 使用std::find查找元素
auto it = std::find(v.begin(), v.end(), stMyTest(50, 51));
if (it != v.end()) {
cout << it->nID << " " << it->nData << endl;
}
// 使用std::find_if查找符合条件的元素
auto it2 = std::find_if(v.begin(), v.end(), stFindID(50));
if (it2 != v.end()) {
cout << it2->nID << " " << it2->nData << endl;
}
return 0;
}
```
std::vector 查找
如果你想在一个 `std::vector` 中查找某个元素,可以使用 `std::find` 算法。例如,以下代码会在一个 `std::vector<int>` 中查找值为 `42` 的元素:
```c++
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 42, 5};
auto it = std::find(vec.begin(), vec.end(), 42);
if (it != vec.end()) {
std::cout << "Found the element " << *it << " at index " << std::distance(vec.begin(), it) << std::endl;
} else {
std::cout << "Could not find the element" << std::endl;
}
return 0;
}
```
`std::find` 算法返回一个指向被查找元素的迭代器,如果找不到,则返回 `end()` 迭代器。在上面的例子中,我们使用 `std::distance` 函数计算出被找到元素的下标。