【C++】判断指定元素是否在vector中的若干种方法小结

every blog every motto: You will never know unless you try
0. 前言 对于判断指定元素是否在vector中小结
1. 正文 1.1 while

#include using namespace std; #includevoid test() { vector v; v.push_back(1); v.push_back(2); v.push_back(3); vector::iterator itBegin = v.begin(); // 起始迭代器 vector::iterator itEnd = v.end(); // 结束迭代器 while (itBegin != itEnd) {cout << *itBegin << endl; if (*itBegin == 2) { cout << "所查元素在其中" << endl; break; } itBegin++; } }int main() { test(); system("pause"); }

1.2 for
#include using namespace std; #includevoid test() { vector v; v.push_back(1); v.push_back(2); v.push_back(3); for (vector::iterator it = v.begin(); it != v.end(); it++) { cout << *it << endl; if (*it == 2) { cout << "所查元素在其中" << endl; break; } } }int main() { test(); system("pause"); }

1.3 find 1.3.1 内置数据类型查找
#include using namespace std; #include #includevoid test() { vector v; for (int i = 0; i < 10; i++) { v.push_back(i); } // 查找是否有5这个元素 vector::iterator it; it = find(v.begin(), v.end(), 5); if (it == v.end()) cout << "没有找到指定元素" << endl; else cout << "找到指定元素" << endl; }int main() { test(); system("pause"); }

1.3.1自定义数据类型查找
需要重载“==”
案例一:
#include using namespace std; #include #include #include// 自定义数据类型查找 class Person { public: Person(string name, int age) { this->m_Name = name; this->m_Age = age; } // 重载== bool operator==(const Person& p) { if (this->m_Name == p.m_Name&&this->m_Age == p.m_Age) { return true; } return false; } public: string m_Name; int m_Age; }; void test022() { vector v; // 创建数据 Person p1("aaa", 1); Person p2("bbb", 2); Person p3("ccc", 3); Person p4("ddd", 4); // 添加数据 v.push_back(p1); v.push_back(p2); v.push_back(p3); v.push_back(p4); vector::iterator it = find(v.begin(), v.end(), p2); if (it == v.end()) { cout << "没有找到" << endl; } else { cout << "找到姓名:" << it->m_Name << " 年龄: " << it->m_Age << endl; }}int main() { test022(); system("pause"); }

案例二:
#include using namespace std; #include #include #include// 自定义数据类型查找// 结构体 struct Point { int x; int y; // 重载== bool operator==(const Point& p) { if (this->x== p.x&&this->y == p.y) { return true; } return false; } }; void test033() { Point point; vectorv; // 创建vector for (int i = 0; i < 4; i++) { point.x = i; point.y = i + 1; v.push_back(point); } // find Point p; p.x = 1; p.y = 1; vector::iterator it = find(v.begin(), v.end(), p); if (it == v.end()) { cout << "没有找到" << endl; } else { cout << "找到了" << endl; } // 遍历打印输出 //for (vector【【C++】判断指定元素是否在vector中的若干种方法小结】::iterator it = v.begin(); it != v.end(); it++) //{ // cout << "x:" << it->x << " y: " << it->y << endl; //} } int main() { test033(); system("pause"); }

    推荐阅读