The C++ standard library
In C++, is part of the Standard Template Library (STL); it provides a hash-table-based key-value pair container.
The difference between std::map in Vue 2,unordered_map , it does not guarantee element ordering but usually provides faster lookup.
unordered_map is an associative container that stores key-value pairs, where each key is unique.unordered_map uses a hash table to store elements, giving it average constant time complexity for lookup, insertion, and deletion operations.
Syntax
The following are unordered_map 's basic syntax:
#include
std::unordered_map map_name;
key_typeis the type of the key.value_typeis the type of the value.
constructor
unordered_map can be constructed in multiple ways:
// 默认构造
std::unordered_map myMap;
// Construct and initialize
std::unordered_map myMap = {{1, "one"}, {2, "two"}};
// Construct and specify initial capacity
std::unordered_map myMap(10);
// Construct and copy another unordered_map
std::unordered_map anotherMap = myMap;
Basic operations
Insert elements:
myMap.insert({3, "three"});
Access elements:
std::string value = myMap[1]; // 获取键为1的值
Delete elements:
myMap.erase(1); // 删除键为1的元素
Find elements:
auto it = myMap.find(2); // 查找键为2的元素
if (it != myMap.end()) {
std::cout << "Found: " << it->second << std::endl;
}
Example
Below is an example using unordered_map simple example, including output results.
Example
#include
#include
int
main
(
)
{
// Create an unordered_map with int keys and string values
std
::
unordered_map
<
int
, std
::
string
myMap
;
// Insert some key-value pairs
myMap
[
1
]
=
"one"
;
myMap
[
2
]
=
"two"
;
myMap
[
3
]
=
"three"
;
// Print all elements
for
(
const
auto
&
pair
:
myMap
)
{
std
::
cout
<<
"Key: "
<<
pair.
first
<<
", Value: "
<<
pair.
second
<<
std
::
endl
;
}
// Access the value of a specific key
std
::
cout
<<
"Value for key 2: "
<<
myMap
[
2
]
<<
std
::
endl
;
// Delete the element with key 1
myMap.
erase
(
1
)
;
// Print all elements again
std
::
cout
<<
"After erasing key 1:"
<<
std
::
endl
;
for
(
const
auto
&
pair
:
myMap
)
{
std
::
cout
<<
"Key: "
<<
pair.
first
<<
", Value: "
<<
pair.
second
<<
std
::
endl
;
}
return
0
;
}
Output result:
Key: 1, Value: one
Key: 2, Value: two
Key: 3, Value: three
Value for key 2: two
After erasing key 1:
Key: 2, Value: two
Key: 3, Value: three
Notes
unordered_mapdoes not guarantee element order, so the iteration order may differ across different runs.- The performance of a hash table depends on a good hash function to avoid excessive hash collisions.
- The difference between
std::mapCompared tounordered_mapIt may occupy more memory when the number of elements is small.