Standard Template Library (STL) - std::map::count

Standard Template Library (STL) - std::map::count

public member function - 公开成员函数

1. std::map::count

size_type count (const key_type& k) const;
Count elements with a specific key - 返回匹配特定键的元素数量

Searches the container for elements with a key equivalent to k and returns the number of matches.
在容器中搜索具有等于 k 的键的元素,并返回匹配数。

Because all elements in a map container are unique, the function can only return 1 (if the element is found) or zero (otherwise).
由于 map 容器中的所有元素都是唯一的,因此该函数只能返回 1 (如果找到了元素) 或零 (否则)。

Two keys are considered equivalent if the container’s comparison object returns false reflexively (i.e., no matter the order in which the keys are passed as arguments).
如果容器的比较对象反射性地返回 false (即,无论键作为参数传递的顺序如何),则两个键被视为等效。

2. Parameters

k
Key to search for. - 搜索关键字。

Member type key_type is the type of the element keys in the container, defined in map as an alias of its first template parameter (Key).
成员类型 key_type 是容器中元素键的类型,在 map 中定义为其第一个模板参数 (Key) 的别名。

3. Return value

1 if the container contains an element whose key is equivalent to k, or zero otherwise.
如果容器包含其键等于 k 的元素,则为 1,否则为零。

Member type size_type is an unsigned integral type.
成员类型 size_type 是 unsigned integral type。

4. Examples

4.1 std::map::count

//============================================================================
// Name        : std::map::count
// Author      : Yongqiang Cheng
// Version     : Version 1.0.0
// Copyright   : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <map>

int main()
{
	std::map<char, int> map_data;
	char c;

	map_data['a'] = 101;
	map_data['c'] = 202;
	map_data['f'] = 303;

	for (c = 'a'; c < 'h'; c++)
	{
		std::cout << c;
		if (map_data.count(c) > 0)
		{
			std::cout << " is an element of map_data.\n";
		}
		else
		{
			std::cout << " is not an element of map_data.\n";
		}
	}

	return 0;
}

a is an element of map_data.
b is not an element of map_data.
c is an element of map_data.
d is not an element of map_data.
e is not an element of map_data.
f is an element of map_data.
g is not an element of map_data.

5. Complexity - 复杂度

Logarithmic in size.
与容器大小成对数。

6. Iterator validity - 迭代器有效性

No changes.

7. Data races - 数据竞争

The container is accessed. - 容器被访问。

No mapped values are accessed: concurrently accessing or modifying elements is safe.
没有映射的值被访问:同时访问或修改元素是安全的。

8. Exception safety - 异常安全性

Strong guarantee: if an exception is thrown, there are no changes in the container.
有力的保证:如果引发异常,则容器中没有任何更改。

References

http://www.cplusplus.com/reference/map/map/count/

发布了443 篇原创文章 · 获赞 1685 · 访问量 101万+

猜你喜欢

转载自blog.csdn.net/chengyq116/article/details/104217068