日期:2021-04-29
作者:19届WY
标签:C++,STL,vector,set,map
C++STL之动态数组vector(矢量的使用)
- 可以在www.cplusplus.com官方网站中直接查询官方文档,上面有方法的讲解和代码示例,(
mac
选手下载Dash
,在里面下载C++
,平时查文档会很方便),Windows
下有离线文档浏览器Zeal
,和Dash
功能一样。下面是vector
常用得一些方法:
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, const char * argv[]) {
vector<int> a ;
cout << a.size() << endl;
for(int i = 0; i < 10; i++){
a.push_back(i);
}
cout << a.size() << endl;
vector<int> b(15);
cout << b.size() << endl;
for(int i = 0; i < b.size(); i++){
b[i] = 15;
}
for(int i = 0; i < b.size(); i++){
cout << b[i] << " ";
}
cout << endl;
vector<int> c(20,2);
for(int i = 0; i < c.size(); i++){
cout << c[i] << " ";
}
cout << endl;
for(auto it = c.begin(); it != c.end(); it++){
cout << *it << " ";
}
return 0;
}
vector
,set
,map
这些容器遍历的时候都使用迭代器,c.begin()
是一个指针,指向容器的第一个元素,c.end()
指向容器的最后一个元素的后一个位置,这里是没有元素的!!!所以迭代器指针it的循环判断条件是it != c.end()
- 访问元素的值要对指针it取值,所以要在前面加上
*
C++STL之集合set的使用
set
是一个集合,里面的元素是各不相同的,而且set
会按照元素进行从小到大的排序,头文件是#include<set>
,下面是一些常用的方法
#include <iostream>
#include<set>
using namespace std;
int main(int argc, const char * argv[]) {
set<int> s;
s.insert(1);
cout << *(s.begin()) << endl;
for(int i = 0; i < 6; i++){
s.insert(i);
}
for(auto it = s.begin();it != s.end(); it++){
cout << *it << " ";
}
cout << endl << (s.find(2) != s.end()) << endl;
cout << (s.find(10) != s.end()) << endl;
s.erase(1);
cout << (s.find(1)!=s.end()) << endl;
return 0;
}
C++STL之映射map的使用
map
是键值对,比如一个人一个学号,就可以定义字符串string
类型的人名为键,int
类型为值,如map<string, int> m
;map
会将所有的键值对按照键从小到大进行排序,头文件是#include<map>
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main(int argc, const char * argv[]) {
map<string, int> m;
m["hello"] = 2;
cout << m["hello"] << endl;
cout << m["world"] << endl;
m["world"] = 3;
m[","] = 1;
for(auto it = m.begin(); it != m.end(); it++){
cout << it->first << " " << it->second << endl;
}
cout << m.begin()->first << " " << m.begin()->second << endl;
cout << m.rbegin()->first << " " << m.rbegin()->second << endl;
cout << m.size() << endl;
return 0;
}