std::map::map

本文详细介绍了C++中map容器的各种构造函数及其使用方法,包括默认构造、范围构造、拷贝构造、移动构造和初始化列表构造等。通过示例展示了不同构造方式的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


explicit map( const Compare& comp = Compare(),
              const Allocator& alloc = Allocator() );
 (until C++14)
map() : map( Compare() ) {}

explicit map( const Compare& comp,

              const Allocator & alloc = Allocator () ) ;
 (since C++14)
explicit map( const Allocator& alloc );
(1)(since C++11)
 (2) 
template< class InputIterator >

map( InputIterator first, InputIterator last,
     const Compare& comp = Compare(),

      const Allocator & alloc = Allocator () ) ;
  
template< class InputIterator >

map( InputIterator first, InputIterator last,

      const Allocator & alloc ) ;
 (since C++14)
map( const map& other );
(3) 
map( const map& other, const Allocator& alloc );
(3)(since C++11)
map( map&& other );
(4)(since C++11)
map( map&& other, const Allocator& alloc );
(4)(since C++11)
 (5) 
map( std::initializer_list<value_type> init,

     const Compare& comp = Compare(),

      const Allocator & alloc = Allocator () ) ;
 (since C++11)
map( std::initializer_list<value_type> init,
     const Allocator& );
 (since C++14)
   

Constructs new container from a variety of data sources and optionally using user supplied allocator alloc or comparison function object comp.

1) Default constructor. Constructs empty container.
2) Constructs the container with the contents of the range [first, last).
3) Copy constructor. Constructs the container with the copy of the contents of other. If alloc is not provided, allocator is obtained by calling std::allocator_traits<allocator_type>::select_on_container_copy_construction(other.get_allocator()).
4) Move constructor. Constructs the container with the contents of other using move semantics. If alloc is not provided, allocator is obtained by move-construction from the allocator belonging to other.
5) Constructs the container with the contents of the initializer list init.

Contents

 [hide

[edit] Parameters

alloc-allocator to use for all memory allocations of this container
comp-comparison function object to use for all comparisons of keys
first, last-the range to copy the elements from
other-another container to be used as source to initialize the elements of the container with
init-initializer list to initialize the elements of the container with
Type requirements
-
InputIterator must meet the requirements of InputIterator.
-
Compare must meet the requirements of Compare.
-
Allocator must meet the requirements of Allocator.

[edit] Complexity

1) Constant
2) N log(N) where N = std::distance(first, last) in general, linear in N if the range is already sorted by value_comp().
3) Linear in size of other
4) Constant. If alloc is given and alloc != other.get_allocator(), then linear.
5) N log(N) where N = init.size()) in general, linear in N if init is already sorted by value_comp().

[edit] Notes

After container move construction (overload (4)), references, pointers, and iterators (other than the end iterator) to other remain valid, but refer to elements that are now in *this. The current standard makes this guarantee via the blanket statement in §23.2.1[container.requirements.general]/12, and a more direct guarantee is under consideration via LWG 2321.

[edit] Example

#include <iostream>
#include <string>
#include <iomanip>
#include <map>
 
template<typename Map>
void print_map(Map& m)
{
   std::cout << '{';
   for(auto& p: m)
        std::cout << p.first << ':' << p.second << ' ';
   std::cout << "}\n";
}
 
int main()
{
  // (1) Default constructor
  std::map<std::string, int> map1;
  map1["something"] = 69;
  map1["anything"] = 199;
  map1["that thing"] = 50;
  std::cout << "map1 = "; print_map(map1);
 
  // (2) Range constructor
  std::map<std::string, int> iter(map1.find("anything"), map1.end());
  std::cout << "\niter = "; print_map(iter);
  std::cout << "map1 = "; print_map(map1);
 
  // (3) Copy constructor
  std::map<std::string, int> copied(map1);
  std::cout << "\ncopied = "; print_map(copied);
  std::cout << "map1 = "; print_map(map1);
 
  // (4) Move constructor
  std::map<std::string, int> moved(std::move(map1));
  std::cout << "\nmoved = "; print_map(moved);
  std::cout << "map1 = "; print_map(map1);
 
  // (5) Initializer list constructor
  const std::map<std::string, int> init {
    {"this", 100},
    {"can", 100},
    {"be", 100},
    {"const", 100},
  };
  std::cout << "\ninit = "; print_map(init);
}

Output:

map1 = {anything:199 something:69 that thing:50 }
 
iter = {anything:199 something:69 that thing:50 }
map1 = {anything:199 something:69 that thing:50 }
 
copied = {anything:199 something:69 that thing:50 }
map1 = {anything:199 something:69 that thing:50 }
 
moved = {anything:199 something:69 that thing:50 }
map1 = {}
 
init = {be:100 can:100 const:100 this:100 }

 
  

 

### C++ `std::map` 使用方法及示例 #### 1. 简介 `std::map` 是 C++ 标准模板库(STL)中的一个关联容器,用于存储键值对。其内部实现基于红黑树,因此具有自动排序特性,并支持高效的插入、删除和查找操作[^2]。 --- #### 2. 基本用法 ##### 2.1 定义和初始化 可以通过多种方式定义并初始化 `std::map`: ```cpp #include <iostream> #include <map> int main() { // 方式一:默认构造 std::map<int, std::string> map1; // 方式二:通过初始列表构造 std::map<int, std::string> map2 = {{1, "one"}, {2, "two"}}; // 方式三:拷贝构造 std::map<int, std::string> map3(map2); return 0; } ``` --- ##### 2.2 插入元素 可以使用以下几种方法向 `std::map` 中插入数据: ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> myMap; // 方法一:使用下标运算符 myMap[1] = "apple"; // 方法二:使用 insert 函数 myMap.insert({2, "banana"}); myMap.insert(std::make_pair(3, "cherry")); // 打印结果 for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; } ``` --- ##### 2.3 查找元素 可通过 `find()` 或下标运算符来访问特定键对应的值: ```cpp #include <iostream> #include <map> int main() { std::map<std::string, int> fruitCount = {{"apple", 3}, {"banana", 5}}; // 使用 find() auto it = fruitCount.find("apple"); if (it != fruitCount.end()) { std::cout << "Found apple with count: " << it->second << std::endl; } // 使用下标运算符 std::cout << "Banana count: " << fruitCount["banana"] << std::endl; return 0; } ``` 注意:如果使用下标运算符访问不存在的键,则会创建该键并将值设为默认值(对于整数类型,默认值为 0)。这可能会导致意外行为[^2]。 --- ##### 2.4 删除元素 可利用 `erase()` 函数删除指定键或范围内的元素: ```cpp #include <iostream> #include <map> int main() { std::map<char, int> charCounts = {{'a', 1}, {'b', 2}, {'c', 3}}; // 删除单个元素 charCounts.erase('b'); // 删除多个元素 charCounts.erase(charCounts.begin(), charCounts.find('c')); for (const auto& pair : charCounts) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; } ``` --- #### 3. 常用函数详解 ##### 3.1 大小与检查是否为空 - `size()` 返回当前映射中键值对的数量。 - `empty()` 判断映射是否为空。 ```cpp #include <iostream> #include <map> int main() { std::map<int, double> data; std::cout << "Size: " << data.size() << ", Empty: " << std::boolalpha << data.empty() << std::endl; data[1] = 3.14; std::cout << "Size after insertion: " << data.size() << ", Empty: " << data.empty() << std::endl; return 0; } ``` --- ##### 3.2 遍历 `std::map` 可以通过迭代器或者基于范围的循环遍历整个映射: ```cpp #include <iostream> #include <map> int main() { std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 85}}; // 迭代器遍历 for (auto it = scores.begin(); it != scores.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; } // 范围基遍历 for (const auto& [key, value] : scores) { std::cout << key << ": " << value << std::endl; } return 0; } ``` --- ##### 3.3 统计键的数量 `count(key)` 可返回给定键是否存在及其数量(通常只为 0 或 1): ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> names = {{1, "John"}, {2, "Jane"}}; std::cout << "Key 1 exists? " << names.count(1) << std::endl; std::cout << "Key 3 exists? " << names.count(3) << std::endl; return 0; } ``` --- ##### 3.4 获取范围 `lower_bound()` 和 `upper_bound()` 提供了获取某个范围内键值的能力: ```cpp #include <iostream> #include <map> int main() { std::map<int, std::string> numbers = {{1, "One"}, {2, "Two"}, {3, "Three"}}; // lower_bound auto lb = numbers.lower_bound(2); std::cout << "Lower bound of 2 is: " << lb->first << " -> " << lb->second << std::endl; // upper_bound auto ub = numbers.upper_bound(2); std::cout << "Upper bound of 2 is: " << ub->first << " -> " << ub->second << std::endl; return 0; } ``` --- #### 4. 注意事项 - **自动排序**:`std::map` 默认按键升序排列,无法更改此顺序[^2]。 - **性能特点**:由于底层采用平衡二叉搜索树,插入、删除和查找的时间复杂度均为 O(log n)[^2]。 --- #### 5. 应用场景 适合需要按键有序存储且频繁执行查找操作的场合。例如,在统计单词频率时,可以用 `std::map` 存储每个单词及其出现次数[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值