///////////////////////////////////////////////////////////// #include "stdafx.h" #include <algorithm> #include <numeric> #include <functional> #include <vector> #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { std::vector<int> nV; std::vector<int>::iterator iter; std::vector<int>::iterator iterBegin; std::vector<int>::iterator iterEnd; // 升序 nV.clear(); nV.push_back(4); nV.push_back(6); nV.push_back(14); nV.push_back(14); nV.push_back(15); nV.push_back(16); nV.push_back(18); nV.push_back(18); nV.push_back(19); iterBegin = nV.begin(); iterEnd = nV.end(); iter = std::lower_bound(iterBegin, iterEnd, 14); // *iter输出14 iter = std::lower_bound(iterBegin, iterEnd, 17); // *iter输出18 iter = std::upper_bound(iterBegin, iterEnd, 14); // *iter输出15 iter = std::upper_bound(iterBegin, iterEnd, 17); // *iter输出18 return 0; }
///////////////////////////////////////////////////////////// #include "stdafx.h" #include <algorithm> #include <numeric> #include <functional> #include <vector> #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { std::vector<int> nV; std::vector<int>::iterator iter; std::vector<int>::iterator iterBegin; std::vector<int>::iterator iterEnd; nV.clear(); nV.push_back(11); nV.push_back(13); nV.push_back(14); nV.push_back(14); nV.push_back(15); // 第1组 nV.push_back(14); // nV.push_back(14); // nV.push_back(16); nV.push_back(17); nV.push_back(16); nV.push_back(15); // 第2组 nV.push_back(14); // nV.push_back(14); // nV.push_back(18); nV.push_back(18); nV.push_back(19); iterBegin = nV.begin(); iterEnd = nV.end(); std::vector<int> nV1; nV1.push_back(15); nV1.push_back(14); nV1.push_back(14); iter = std::search(iterBegin, iterEnd, nV1.begin(), nV1.end()); // 返回上面"第1组"第一个元素所在的迭代器 nV1.clear(); nV1.push_back(40); nV1.push_back(14); nV1.push_back(14); nV1.push_back(14); iter = std::search(iterBegin, iterEnd, nV1.begin(), nV1.end()); // 返回nV.end(); return 0; }说明:
1. find_end查找到最后一组就返回, 而search查找到第一组就返回
///////////////////////////////////////////////////////////// #include "stdafx.h" #include <algorithm> #include <numeric> #include <functional> #include <vector> #include <iostream> int _tmain(int argc, _TCHAR* argv[]) { std::vector<int> nV; std::vector<int>::iterator iter; std::vector<int>::iterator iterBegin; std::vector<int>::iterator iterEnd; nV.clear(); nV.push_back(11); nV.push_back(13); nV.push_back(14); // A nV.push_back(14); nV.push_back(15); nV.push_back(14); // B nV.push_back(14); nV.push_back(16); nV.push_back(17); nV.push_back(16); nV.push_back(15); nV.push_back(14); // C nV.push_back(14); nV.push_back(18); nV.push_back(18); nV.push_back(19); iterBegin = nV.begin(); iterEnd = nV.end(); iter = std::search_n(iterBegin, iterEnd, 2, 14); // 返回A处迭代器 iter = std::search_n(iterBegin, iterEnd, 3, 14); // 返回nV.end(); return 0; }