您的位置:首页 > 其它

3.1.3 STL中list、map、vector的使用方法

2015-05-12 13:25 387 查看
(一)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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: