c++ map swap使用

这篇博客介绍了C++中map的swap方法,通过`a.swap(b)`可以实现两个map内容的互换。该操作高效地将b的内容转移给a,而不仅仅是复制。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <fstream>
#include <string.h>
#include <sys/stat.h>
#include <vector>
#include <map>

using namespace std;


void show(std::map<int, std::string> framebuffer)
{
   
	auto matinfo_iter = framebuff
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++的unordered_map是一种关联容器,它提供了一种键值对的映射关系。swap函数是unordered_map类的一个成员函数,用于交换两个unordered_map对象的内容。 unordered_mapswap函数的语法如下: ```cpp void swap(unordered_map& other); ``` 其中,other是另一个unordered_map对象,表示要与当前unordered_map对象进行交换的对象。 使用swap函数可以快速高效地交换两个unordered_map对象的内容,而不需要逐个元素进行复制或移动。这在某些情况下可以提高程序的性能。 下面是一个示例代码,展示了如何使用swap函数交换两个unordered_map对象的内容: ```cpp #include <iostream> #include <unordered_map> int main() { std::unordered_map<int, std::string> map1 = {{1, "apple"}, {2, "banana"}}; std::unordered_map<int, std::string> map2 = {{3, "orange"}, {4, "grape"}}; std::cout << "Before swap:" << std::endl; for (const auto& pair : map1) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << std::endl; for (const auto& pair : map2) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << std::endl; map1.swap(map2); std::cout << "After swap:" << std::endl; for (const auto& pair : map1) { std::cout << pair.first << ": " << pair.second << std::endl; } std::cout << std::endl; for (const auto& pair : map2) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; } ``` 输出结果: ``` Before swap: 1: apple 2: banana 3: orange 4: grape After swap: 3: orange 4: grape 1: apple 2: banana ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值