在c++中封装好的stack,queue,list,vector中使用迭代器 定义 如vector<int>::iterator it;
数组用指针,已封装好的结构体用迭代器;
lower_bound采用二分搜索;
begin():返回指向容器开头的迭代器;
end():返回指向容器末尾的迭代器,这里的末尾指的是最后一个元素的下一个位置;
lower_bound(数组首地址/迭代器头,数组尾/迭代器尾,value)
distance(首地址,求出value的地址)(用于数组和vector中判断位置)
1 #include<iostream> 2 #include<algorithm> 3 4 using namespace std; 5 6 int main() 7 { 8 int A[14] = {1 ,1, 2, 2, 2, 4, 5, 5, 6, 8, 8, 8, 10, 15 }; 9 int *pos; //数组用指针 10 int idx; 11 pos = lower_bound(A, A+14, 3); //value地址 12 idx = distance(A, pos); //到首地址的距离 13 cout << "A[" <<idx<< "] = " << *pos << endl; 14 15 pos = lower_bound(A, A+14, 2); 16 idx = distance(A, pos); 17 cout << "A[" << idx <<"] = " << *pos <<endl; 18 19 return 0; 20 }
下面是用vector写,使用迭代器
1 #include<iostream> 2 #include<algorithm> 3 #include<vector> 4 using namespace std; 5 6 int main() 7 { 8 vector<int> A; 9 A.push_back(1); 10 A.push_back(2); 11 A.push_back(3); 12 A.push_back(4); 13 A.push_back(5); 14 A.push_back(6); 15 16 vector<int> ::iterator pos; //定义迭代器 17 int idx; 18 pos = lower_bound(A.begin() , A.end() , 3); 19 idx = distance(A.begin() , pos); 20 cout << "A[" <<idx<< "] = " << *pos << endl; 21 22 pos = lower_bound(A.begin() , A.end(), 2); 23 idx = distance(A.begin() , pos); 24 cout << "A[" << idx <<"] = " << *pos <<endl; 25 26 return 0; 27 }