C++ std set和map

set和map都是std标准库中的模板类型,对成员和内存有着好的管理

set

  1. set中的元素都是排好序的
  2. set集合中没有重复的元素
#include <set> 

set<int> s;   //定义一个set容器 类型为int型
s.begin()     //返回指向第一个元素的迭代器
s.clear()     //清除所有元素
s.count()     //返回bool型,有返回1,无返回0
s.empty()     //如果集合为空,返回true
s.end()       //返回指向最后一个元素之后的迭代器,不是最后一个元素
s.erase()     //删除集合中的元素
s.find()      //返回一个指向被查找到元素的迭代器,如果没找到则返回end()
s.insert()    //在集合中插入元素
s.size()      //集合中元素的数目
s.swap()      //交换两个集合变量

for(set<int>::iterator it = s.begin(); it != s.end(); ++it){ //遍历 
    cout << *it << endl;
}

map

#include <map>

map<k, v> m;            //创建一个名为m的空map对象,其键和值的类型分别为k和v
map<k, v> m(m1);        //创建m1的副本m,m与m1必须有相同的键类型和值类型
map<k, v> m(b, e);      //创建map类型的对象m,存储迭代器b和e标记的范围内所有元素的副本。元素的类型必须能转换为pair<const k, v>

map<K, V>::key_type     //在map容器中,用做索引的键的类型
map<K, V>::mapped_type  //在map容器中,键所关联的值的类型
map<K, V>::value_type   //一个pair类型,它的first元素具有const map<K, V>::key_type类型,而second元素则为map<K, V>::mapped_type类型
#include <bits/stdc++.h>
using namespace std;
int main(){
    map<string, int> words;
    cout << words["bug"] << endl;     //0
    ++words["bug"];                   //插入
    cout << words["bug"] << endl;     //1
    return 0;
}

【题解】小信的面试

题目描述

小信来应聘程序员的时候,曾经遇到这样一个面试题:
给定 n 个整数,求里面出现次数最多的数,如果有多个重复出现的数,求出值最大的一个。当时可算是给小信难住了。现在小信来考考你。

输入

第一行输入一个整数 n(1 <= n <= 100000),接下来一行输入 n 个 int 范围内的整数。

输出

输出出现次数最多的数和出现的次数,中间用一个空格隔开,如果有多个重复出现的数,输出值最大的那个。

样例1

输入

5
1 1 2 3 4

输出

1 2

样例2

输入

10
9 10 27 4 9 10 3 1 2 6

输出

10 2

题解

#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
map<int, long long> N;
int main(){
	long long n;
	cin >> n;
	for(long long i = 0; i < n; ++i){
		int a;
		cin >> a;
		++N[a];
	}
	int many = 0, num;
	for(map<int, long long>::iterator it = N.begin(); it != N.end(); ++it){
		if((*it).second >= many){
			many = (*it).second;
			num = (*it).first;
		}
	}
	cerr << num << " " << many;
	return 0;
}
发布了6 篇原创文章 · 获赞 5 · 访问量 776

猜你喜欢

转载自blog.csdn.net/weixin_45425652/article/details/104032133