[LeetCode刷题笔记] C++ unordered_map常用操作

在[1]对常用的STL容器进行了概览,笔者在刷题过程中经常需要查询一些STL容器的函数,实为不便,因此在此对STL容器中常用的操作进行笔记。


在这里插入图片描述

std::unordered_map<key, T> 是一种关联性的容器,类似于Python中的dict字典,其特点就是可以通过键值key在近似于常数时间内进行内容的检索和修改等。注意到其和std::map不同的一点是,其是无序的,也就是说插入的元素排序是没有规律的。在unordered_map中如果插入重复的键值,那么后来者将会被忽略,而不是取代,这点需要注意。

std::unordered_map的类声明原型如:

template < class Key,                                    // unordered_map::key_type
           class T,                                      // unordered_map::mapped_type
           class Hash = hash<Key>,                       // unordered_map::hasher
           class Pred = equal_to<Key>,                   // unordered_map::key_equal
           class Alloc = allocator< pair<const Key,T> >  // unordered_map::allocator_type
           > class unordered_map;

通常来说,我们需要指定的是键值key和内容物T的类型,如同string,int,char等,键值和内容物的类型可以不同。一般来说,我们会用到的关于无序map的函数操作有:

  1. find() 根据键值,查找某个元素,返回迭代器,如果没找到元素,则返回unordered_map.end()迭代器,指示没有该元素。
  2. count() 查找无序map中元素为指定键值的元素的数量,因为无序map不允许重复的键值,因此如果能找到该元素,则返回1,否则返回0。
  3. insert() 插入元素,如果是重复键值,注意,该插入将会被忽略。
  4. erase() 通过指定键值或者迭代器,可以删除元素。
  5. clear() 清空容器内容。
  6. empty() 判断是否为空容器。
  7. size() 返回容器大小。

通过以下的例子,我们将会学会在一般使用中如何初始化和使用无序map:

#include <unordered_map>
#include <string>
using namespace std;

int main() {
	unordered_map<int, string> m = {{1, "apple"}, {2,"watermelon"}};
	
	// 插入操作示例
	pair<int, string> instance (3, "grape");
	m.insert(instance);
	m[4] = "banana";

	// 查找
	auto got = m.find(4);
	if (got == m.end())
		cout << "not found" << end;
	else
		cout << "found" << got->first << "is" << got->second << endl; 
		// 也可以通过*got取内容

	// 检索
	cout << m[1] << endl; // 如果键值不存在,则会抛出异常,因此一般可以先进行查找后再索引。

	// 修改
	m[1] = 'orange';

	// 删除元素
	m.erase(m.begin()); // 通过指定迭代器
	m.erase(1); 通过指定键值

	// 清空
	m.clear(); 
	
}

Reference

[1]. https://blog.csdn.net/LoseInVain/article/details/104189784

发布了127 篇原创文章 · 获赞 219 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/LoseInVain/article/details/104466284