STL tips (continuously updated)

The use of the map collection:
traversal

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

Skill

    for (int i = 0; i < n; i++){
        cin >> a[i];
        for(int j = 0; j < a[i].size(); j++){
            mp[a[i].substr(j)]++;
        }
    }
    for (int i = 0; i < n; i++)
        cout << mp[a[i]] << "\n";

The use of stack in stack
STL

    while(true){
        cin >> c;
        if(c == 0) break;
        a.push(c);//将括号里的元素压入stack顶部 
    }
    while(!a.empty()){
        cout<<a.top()<<" ";//.top()是一个返回stack顶部元素的函数 
        a.pop();//删除stack顶部的元素 
    }

The use of vector dynamic array
STL vector STL can completely not worry about the size of the array, this is similar to string

    while(true){//有时候也可以巧用死循环 
        cin >> c;
        if(c == 0) break;//终止条件 
        a.push_back(c);//将括号里的元素压入vector尾部 
    }
    while(!a.empty()){
        cout << a.back() << " ";//.back()是一个返回vector尾部元素的函数 
        a.pop_back();//删除vector尾部的元素
    }
    //要注意vector是从a[0]开始存储a.size()个元素,要当心越界访问
}

Traversal of vector

	vector<string>::iterator it;
    it = v.begin();
    while(it != v.end()){
        cout << *it << " " << endl;
        it ++; 
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325685975&siteId=291194637