3.1.3 STL中list、map、vector的使用方法
阿新 • • 發佈:2019-01-29
(一)list的使用方法:
程式碼:
#include <iostream> #include <list> #include <algorithm> #include <numeric> #include <iterator> using namespace std; typedef list<int> LISTINT; typedef list<char> LISTCHAR; int main() { LISTINT listA; LISTINT::iterator it1; listA.push_front(2); listA.push_front(1); listA.push_back(3); listA.push_back(4); for(it1 = listA.begin(); it1 != listA.end(); ++it1) { cout << *it1; } cout << endl; for(LISTINT::reverse_iterator it2 = listA.rbegin(); it2 != listA.rend(); ++it2) { cout << *it2; } cout << endl; //使用STL裡面的演算法,求容器中所有元素之和 int sum = accumulate(listA.begin(), listA.end(), 0); cout << sum << endl; LISTCHAR listB; LISTCHAR::iterator it3; listB.push_front('A'); listB.push_front('B'); listB.push_back('C'); listB.push_back('D'); for(it3 = listB.begin(); it3 != listB.end(); ++it3) { cout << char(*it3); } cout << endl; //使用STL裡面的演算法,求容器中的最的的元素 it3 = max_element(listB.begin(), listB.end()); cout << char(*it3) << endl; return 0; }
(二)map使用方法:
程式碼:
#include <iostream> #include <map> #include <algorithm> #include <iterator> #include <string> using namespace std; int main() { map<string, string> student; //三種插入方法 student.insert(pair<string, string>("zhangsan", "3")); student.insert(map<string, string>::value_type("lisi", "4")); student["wangwu"] = "5"; //查詢 map<string, string>::iterator iter; iter = student.find("zhangsan"); if(iter == student.end()) cout << "can not find zhangsan" << endl; else cout << "find zhangsan" << endl; //刪除 iter = student.find("zhangsan"); if(iter == student.end()) cout << "can not find zhangsan" << endl; else student.erase(iter); return 0; }
(三)vector的使用方法。
程式碼:
#include <iostream> #include <vector> #include <string> using namespace std; int main() { vector<int> vec; vec.push_back(1); vec.push_back(2); cout << vec.size() << endl; cout << vec.capacity() << endl; if(!vec.empty()) cout << "vec not NULL" << endl; return 0; }