【刷题】C++刷题中常用的STL中相关内容

处理题目的输入输出

1 vector中,pairtuple类型使用


pair<int, int> node = make_pair(0, 1);
vector<pair<int, int> > vec;
vec.push_back(node);

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

#include <iostream>
#include <tuple>
#include <set>
#include <vector>
#include <algorithm>

using namespace std;

void Test()
{
	vector<pair<int, int>> vp;
	vp.emplace_back(make_pair(10, 9));
	vp.emplace_back(10, 12);
	vp.emplace_back(11, 9);
	vp.emplace_back(10, 9);

	sort(vp.begin(), vp.end());
	//vp.erase(make_pair(10, 12));
	 for (auto it = vp.begin(); it != vp.end(); it++) {
	     if (it->first == 10 && it->second == 12) {
	         vp.erase(it);
	         break;
	     }
	 }

	for (auto& it : vp) {
		cout << it.first << " " << it.second << endl;
	}

	set<tuple<int, int, int>> st;
	st.emplace(10, 11, 13);
	st.emplace(10, 12, 9);
	st.emplace(10, 12, 10);
	st.emplace(9, 12, 10);
	cout << "Before st erase" << endl;
	for (auto &it : st) {
		cout << get<0>(it) << " " << get<1>(it) << " " << get<2>(it) << endl;
	}
	st.erase({ 10, 12, 9 });

	cout << "After st erase" << endl;
	for (auto &it : st) {
		cout << get<0>(it) << " " << get<1>(it) << " " << get<2>(it) << endl;
	}

	set<pair<int, int>> sp;
	sp.emplace(10, 3);
	sp.emplace(10, 2);

	sp.erase({ 10, 3 });
	cout << sp.begin()->first << " " << sp.begin()->second << endl;

}

int main()
{
	Test();
	return 0;

}

2 mapunordered_map

1. 遍历(正序&&逆序)

unordered_map<string, int> umap;
// 正序遍历
for (auto &mp :  umap) {
		cout << mp.first << " " << mp.second << endl;
}
// 逆序遍历map
map<int, string> mmap;
for  (auto itr = mmap.rbegin(); itr != mmp.rend(); itr++) {
		cout << itr->first << " " << itr->second << endl;
}

插入元素–将返回插入位置的迭代器

map<string, int> mp;
map<string, int>::iterator itr = mp.insert(pair<string, int>(value, timestamp));
map<string, int>::iterator itr = mp.insert(make_pair(value, timestamp));
size_type count(const key_type& key);		// 容器中是否存在指定键值
size_type erase(const key_type& key);		// 删除指定键值
unordered_map<int, int> counter;
counter[num]++											// 如果num不存在,counter[num] = 0; 否则counter[num] = counter[num] + 1;

3 string

0. 字符串中双指针

一个指针遍历给定字符串s;
另一个指针遍历新建的结果字符串t;

1. 求子串

string str = "Hello World!\n";
string sub = str.substr(6, 5);

2.根据分隔符分割字符串

#include <sstring>
#include <string>
#include <iostream>

void func(string& str)
{
	stringstream ss(str);
	string item;
	vector<string> vec;
	while (getline(ss, item, ',') {
		vec.push_back(item);
	}
}

int main()
{
	return 0;
}

3. 字符串与int数字互转

// 字符串转数字
#include <stdio.h>
string str = "123";
int num = atoi(str.c_str());

// 数字转字符串
string to_string(int num);

4.字符串查找函数的使用

string str = "123456789";
   string::size_type pos = str.find("09");
   if (pos != string::npos) { ;
       cout << pos << endl;
   }

find_last()

find_last_of()

// string::find_last_of
#include <iostream>       // std::cout
#include <string>         // std::string
#include <cstddef>         // std::size_t

void SplitFilename (const std::string& str)
{
  std::cout << "Splitting: " << str << '\n';
  std::size_t found = str.find_last_of("/\\");
  std::cout << " path: " << str.substr(0,found) << '\n';
  std::cout << " file: " << str.substr(found+1) << '\n';
}

int main ()
{
  std::string str1 ("/usr/bin/man");
  std::string str2 ("c:\\windows\\winhelp.exe");

  SplitFilename (str1);
  SplitFilename (str2);

  return 0;
}

5.字符串逆序

reverse(res.begin(), res.end());

6.转成小写字母

string str = "adfa";
tolower(str[i]);

7.删除字符串

s.erase(6, 2)			# 删除s中序号为6,长度为2的字符串

8. 判断字符是否为数字或字符

char c;
c = getchar();
//来判断是否为数字,如果是数字那么会返回非0
if(isdigit(c) != 0)
    printf("是数字\n") ;
//来判断是否为字母,如果是字母那么返回非0
else if(isalpha(c) != 0)
    printf("是字母\n"); 
else
    printf("是特殊字符\n");

7.弹出最后一个元素

string str;
str.pop_back();		# 弹出最后一个元素;
str.back();				# 访问最后一个元素;

4 二分搜索

5 栈和队列的输入输出

int val = 3;
stack<int> st;
st.push(val);			# 压入元素
st.top();					# 访问栈顶元素
st.pop();					# 弹出栈顶元素

queue<int> qu;
qu.push()					#  将元素压入队尾
qu.front()					# 访问队首元素
qu.pop()					# 弹出队首元素

6 vector常用接口

int n = 10;
vector<int> nums(n, 0);
bool empty();													// 判断容器是否为空
size_type size();												// 返回容器中元素数量
void push_back(const value_type& val);			// 将元素压入容器末尾
void pop_back();					// 弹出最后一个元素
reference back();					 // 返回最后一个元素的引用

emplace_back()					// 插入元素
swap(nums[0], nums[1]);		// 交换下表0和小标为1的两个元素的值

7 string常用接口

string str = "abc";
size_type size();
bool empty();

void push_back();
void pop_back();
back();
string substr(size_t pos, size_t len);

9 set常用接口

9.3 set 和 multiset

void FunSet()
{
	multiset<int> st;
	st.insert(5);
	st.insert(6);
	st.insert(5);
	st.insert(5);
	st.insert(6);

	st.erase(st.begin());		// 删除第一个元素
	//st.erase(st.rbegin());		// 出错
	st.erase(--st.end());			// 删除st最后一个元素
	st.erase(*st.begin());		// 将所有的5全部删除
}

9.2 unordered_set

size_type count(const key_type& key);
bool empty();	
insert(const key_type& key);
size_type erase(const key_type& key);			// 删除成功返回1, key不存在返回0;

10 list常用接口


front();
back()

push_back();
pop_back();

push_front();
pop_front();

reverse_iterator与iterator之间的转换;

class BrowserHistory {
public:
    BrowserHistory(string homepage) {
        lstURL.push_back(homepage);
        pcur = lstURL.begin();
    }
    
    void visit(string url) {
        // 访问新网址前,把正在浏览的一直到最后都删掉
        auto pnext = next(pcur);
        while (pnext != lstURL.end()) {
            lstURL.erase(pnext);
            pnext = next(pcur);
        }
        lstURL.push_back(url);
        // 指向最新访问的
        pcur = prev(lstURL.end());
    }
    
    string back(int steps) {
        while (steps-- && pcur != lstURL.begin()) {
            pcur--;
        }
        return *pcur;
    }
    
    string forward(int steps) {
        while (steps-- && next(pcur) != lstURL.end()) {
            ++pcur;
        }
        return *pcur;
    }
private:
    list<string> lstURL;
    // 指示当前正在浏览的
    list<string>::iterator pcur;
};

/**
 * Your BrowserHistory object will be instantiated and called as such:
 * BrowserHistory* obj = new BrowserHistory(homepage);
 * obj->visit(url);
 * string param_2 = obj->back(steps);
 * string param_3 = obj->forward(steps);
 */

11 特殊函数

string str = "12ab";
if (isdigital(str[i]) != 0) {
	cout << "是数字" << endl;
}

12 自定义hash



class MovieRentingSystem {
private:
    // # 需要自行实现 pair<int, int> 的哈希函数
    // static constexpr auto pairHash = [fn = hash<int>()](const pair<int, int>& o) {return (fn(o.first) << 16) ^ fn(o.second);};

    struct pair_hash {
        template<class T1, class T2>
        std::size_t operator () (const std::pair<T1, T2>& p) const {
            auto h1 = std::hash<T1>{} (p.first);
            auto h2 = std::hash<T2>{} (p.second);
            return h1 ^ h2;
        }
    };

    //unordered_map<pair<int, int>, int, decltype(pairHash)> t_price{0, pairHash};
    unordered_map<pair<int, int>, int, pair_hash> t_price;

    unordered_map<int, set<pair<int, int>>> t_valid;

    set<tuple<int, int, int>> t_rent;

public:
    MovieRentingSystem(int n, vector<vector<int>>& entries) {
        for (const auto& entry: entries) {
            t_price[{entry[0], entry[1]}] = entry[2];
            t_valid[entry[1]].emplace(entry[2], entry[0]);
        }
    }
    
    vector<int> search(int movie) {
        if (!t_valid.count(movie)) {
            return {};
        }
        
        vector<int> ret;
        auto it = t_valid[movie].begin();
        for (int i = 0; i < 5 && it != t_valid[movie].end(); ++i, ++it) {
            ret.push_back(it->second);
        }
        return ret;
    }
    
    void rent(int shop, int movie) {
        int price = t_price[{shop, movie}];
        t_valid[movie].erase({price, shop});
        t_rent.emplace(price, shop, movie);
    }
    
    void drop(int shop, int movie) {
        int price = t_price[{shop, movie}];
        t_valid[movie].emplace(price, shop);
        t_rent.erase({price, shop, movie});
    }
    
    vector<vector<int>> report() {
        vector<vector<int>> ret;
        auto it = t_rent.begin();
        for (int i = 0; i < 5 && it != t_rent.end(); ++i, ++it) {
            ret.emplace_back(initializer_list<int>{get<1>(*it), get<2>(*it)});
        }
        return ret;
    }
};

/**
 * Your MovieRentingSystem object will be instantiated and called as such:
 * MovieRentingSystem* obj = new MovieRentingSystem(n, entries);
 * vector<int> param_1 = obj->search(movie);
 * obj->rent(shop,movie);
 * obj->drop(shop,movie);
 * vector<vector<int>> param_4 = obj->report();
 */

13 priority_queue<int, vector, greater>

  1. 小根堆的简单使用
class KthLargest {
public:
        priority_queue<int, vector<int>, greater<int>> pq;
        int k;

        KthLargest(int k, vector<int> arr) {
            this->k = k;
            for (auto &it : arr) {
                add(it);
            }
        }

        int add(int n) {
            pq.push(n);
            if (pq.size() > k) {
                pq.pop();
            }
            return pq.top();
        }
};
  1. 建立pair的小顶堆
class Solution {
public:
    static bool cmp(pair<int, int>& m, pair<int, int>& n) {
        return m.second > n.second;
    }

    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> occurences;
        for (auto &v : nums) {
            occurences[v]++;
        }

        // pair第一个元素表示数组值,第二个元素表示出现次数;
        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(&cmp)> q(cmp);
        for (auto& [num, count] : occurences) {
            if (q.size() == k) {
                if (q.top().second < count) {
                    q.pop();
                    q.emplace(num, count);
                }
            } else {
                q.emplace(num, count);
            }
        }

        vector<int> res;
        for (; !q.empty(); ) {
            res.push_back(q.top().first);
            q.pop();
        }
        return res;
    }
};

20221111考试总结:

  1. multiset头文件不清楚:1244. 力扣排行榜
  2. 设计题调试方法不熟悉;
  3. 自定义pair_hash不会写;
#include <iostream>

#include <unordered_map>
#include <unordered_set>
#include <map>
#include <set>

using namespace std;

struct hash_pair {
    std::size_t operator() (const pair<int, int>& p)const {
        auto h1 = hash<int>{} (p.first);
        auto h2 = hash<int>{} (p.second);
        return h1 ^ h2;
    }
};

void fun()
{
    unordered_map<pair<int, int>, int, hash_pair> umap;
    umap[make_pair(1, 2)] = 3;

    multiset<int> ms;
    ms.insert(3);
    ms.insert(3);

    for (auto is : ms) {
        cout << is << endl;
    }

    set<int> s(ms.begin(), ms.end());
    for (auto is : s) {
        cout << is << endl;
    }
    
}


int main()
{
    fun();
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值