您的位置:首页 > 其它

STL中一些容器的使用

2016-08-05 15:54 351 查看
1. vector

小例子

#include "stdafx.h"

#include <vector>

#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{
vector<int> iv(2, 9);
iv.push_back(1);
iv.push_back(2);
iv.push_back(3);
int i;
for (i = 0; i < (int)iv.size(); i++)
{
cout << iv[i] << ' ';
}

cout<< endl;

vector<int>::iterator ite;
for (ite = iv.begin(); ite != iv.end(); ite++)
{
cout << *ite << ' ';
}

cout << endl;

cout << "size=" << iv.size() << endl;
cout << "capacity=" << iv.capacity() << endl;

getchar();

return 0;

}

2. list

小例子

#include "stdafx.h"

#include <list>

#include <iostream>

#include <algorithm>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{
list<int> ilist;

int i;
for (i = 0; i < 5; i++)
{
ilist.push_back(i);
}

list<int>::iterator ite;

int key = 3;
ite = find(ilist.begin(), ilist.end(), key);

if (ite != ilist.end())
{
ilist.insert(ite, 99);
}
else
{
cout << "没有找到" << key << endl;
}

for (ite = ilist.begin(); ite != ilist.end(); ite++)
{
cout << *ite << ' ';
}

getchar();
return 0;

}

3. map

小例子

#include "stdafx.h"

#include <map>

#include <iostream>

#include <string>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{
map<int, string> testMap;

//增加元素
testMap.insert(make_pair(1, "a"));
testMap.insert(make_pair(2, "b"));
testMap.insert(make_pair(3, "c"));
testMap.insert(make_pair(4, "d"));
testMap.insert(make_pair(5, "e"));

map<int, string>::iterator ite;
for (ite = testMap.begin(); ite != testMap.end(); ite++)
{
cout << ite->first << "  " << ite->second << endl;
}
cout << endl;

//删除元素
ite = testMap.find(3);
if (ite != testMap.end())
{
testMap.erase(ite);
}

for (ite = testMap.begin(); ite != testMap.end(); ite++)
{
cout << ite->first << "  " << ite->second << endl;
}
cout << endl;

//修改元素
ite = testMap.find(5);
if (ite != testMap.end())
{
ite->second = "eee";
}

for (ite = testMap.begin(); ite != testMap.end(); ite++)
{
cout << ite->first << "  " << ite->second << endl;
}
cout << endl;

//查找元素
ite = testMap.find(2);
if (ite != testMap.end())
{
cout << ite->first << "  " << ite->second << endl;
}

getchar();
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: