C++常用数据结构备忘

版权声明:不短不长八字刚好@wzy https://blog.csdn.net/qq_38089964/article/details/84486168

1.优先队列(priority_queue):堆排序

常用函数:

  1. push(value):放入元素

  2. pop():删除优先级最高的元素

  3. top():返回优先级最高的元素

#include <vector>
#include<queue>
#include <iostream>
using namespace std;
struct cmp {//重载比较函数 
  bool operator()(int a,int b) {
    return a < b;  
  }
};
int main() {
  priority_queue<int,vector<int>,cmp> q;//第一个为存储的类型,第二个为存储方式,第三个为比较器 
  q.push(15);
  q.push(455);
  q.push(1);
  q.push(3);
  q.push(2);
  while(!q.empty()) {
    cout << q.top() << endl;
    q.pop();
  }
  return 0;
}

2.vector:可以用作队列(先进先出),栈(最后进最后出),list(顺序表):

主要用到的函数:

  1. push_back(value):追加到最后
  2. back():获取最后的元素
  3. front():获取第一个元素
  4. erase(迭代元素):删除元素:erase(v1.begin() + i):删除下标为i的元素
  5. insert():插入元素;insert(v1.begin()+i,value):插入到下标为i的位置

#include<iostream>
#include<string>
#include<vector>
using namespace std;

void stack() {
	vector<int> v1;
	v1.push_back(12);
	v1.push_back(13);
	v1.push_back(14);
	v1.push_back(15);
	while (!v1.empty()) {
		cout << v1.back() << endl;//导出最后的元素
		v1.pop_back();
	}
}
void queue() {
	vector<int> v1;
	v1.push_back(12);
	v1.push_back(13);
	v1.push_back(14);
	v1.push_back(15);
	while (!v1.empty()) {
		cout << v1.front() << endl;//导出最后的元素
		v1.erase(v1.begin());
	}
}

void list() {
	vector<int> v1;
	v1.push_back(12);
	v1.insert(v1.begin() + 1,11);
	v1.insert(v1.begin() + 1,56);
	v1.insert(v1.begin() + 1,88);
	for (int i = 0; i < v1.size(); i++) {
		cout << v1[i] << endl;
	}
}
int main() {
//	stack();
//	queue();
	list();
	return 0;
}

3.map:(映射表)

常用函数:

  1. map[key]=value;直接插入
  2. map[key];直接获取
  3. count(key):查看是否有key,如果有返回1,否则返回0
  4. find(key):返回迭代器元素
  5. erase(迭代器元素):删除元素;erase(myMap.find(key));删除key的元素
    #include<iostream>
    #include<map>
    #include<string>
    using namespace std;
    
    //定义学生id和学号的关系,遍历
    void foreach() {
      map<int, string > myMap;
      //添加元素 
      myMap[1] = "5120162154";
      myMap[2] = "1547784655";
      myMap[3] = "88786656455";
      //遍历
      map<int, string>::iterator it;
      for (it = myMap.begin(); it != myMap.end(); it++) {
        cout << it->first << " " << it->second << endl;
      }
    }
    
    //对每个人的成绩累加
    void demo() {
      int n = 10;
      map<int, int> scores;//每个人的总分
      for (int i = 0; i < n; i++) {
        int id = i % 2;
        if (!scores.count(id)) {
          scores[id]=0;
          cout << "第一次得分,初始化为0\n";
        }
        scores[id] += i;
      }
    
      //删除元素
      if (scores.count(33)) {
        scores.erase(scores.find(33));
      }
      map<int, int>::iterator it;
      for (it = scores.begin(); it != scores.end(); it++) {
        cout << it->first << " " << it->second << endl;
      }
    }
    int main() {
      foreach();
      demo();
    }

猜你喜欢

转载自blog.csdn.net/qq_38089964/article/details/84486168