c++语法备忘录

来源:互联网 发布:photoshop8 mac破解版 编辑:程序博客网 时间:2024/06/05 11:55

1.STL容器

(1)初始化

//用数组初始化vector<vector<int>> nums{ {1,2},{3,4} };vector<string> ss{ "Hello", "Alaska", "Dad", "Peace" };//用一种容器来初始化vector<int>nums1{1,2,3};set<int> s(nums1.begin(), nums1.end());//初始化为固定值vector<int> temp(10,0);//长度为10,每个元素初始化为0vector<vector<int>> temp(10, vector<int>(10, 1));//map  (key,value)map<int,int> dict;map<int, int> dict{ {1,1},{2,2},{3,3} };//直接初始化//插入数据dict[1]=1;//查找key为1是否在dict中,如果不存在则插入一个新对象,存在即赋值//插入单条记录dict.insert(pair<int,int>(1,1))dict.insert(make_pair<int,int>(1,1))dict.insert(map<int, int>::value_type(1, 3));//指定位置插入map<int,int>::iterator it=dict.begin();dict.insert(it, pair<int, int>(2, 5));//插入多条记录map<int,int> temp;temp.insert(dict.begin(),dict.end());//迭代器temp.insert({ {1,1},{2,3} });//列表

(2)遍历

//老方法for(int i=0;i<vec.size();i++)    cout<<vec[i]<<endl;//新方法,c++11新增for (auto val : valList){    cout << val << endl;}//map遍历for (auto p : dict)        cout << p.first << " " << p.second << endl;

2.STL函数

(1)count,count_if
count (InputIterator first, InputIterator last, const T& val);
对某个元素计数

string s="hello, it's me!'int c_count=count(s.begin(),s.end(),'e')

count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
对满足某条件的元素计数

bool fun(int a){ return a%2==0;}vector<int> v{1,2,3,3,4,8,10,13,17,20}int c_count=count_if(v.begin(),v.end(),fun)
0 0