首页 > 其他分享 >16.map插入方式有哪几种?

16.map插入方式有哪几种?

时间:2023-08-02 22:57:42浏览次数:27  
标签:myrecipe map contains insert 插入方式 插入 哪几种 pair

16.map插入方式有哪几种?

1.用insert函数插入pair数据

mapStudent.insert(pair<int, string>(1, "student_one")); 

2.用insert函数插入value_type数据

mapStudent.insert(map<int, string>::value_type (1, "student_one"));

3.在insert函数中使用make_pair()函数

mapStudent.insert(make_pair(1, "student_one")); 

4.用数组方式插入数据

mapStudent[1] = "student_one"; 
unordered_map < string, double> myrecipe, mypantry = { {"milk",2.0},{"flour",1.5} };
/****************插入*****************/

pair<string, double> myshopping("baking powder", 0.3);
myrecipe.insert(myshopping);                        // 复制插入
myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // 移动插入
myrecipe.insert(make_pair("banana", 6.0)); //在insert函数中使用make_pair()函数
myrecipe.insertt(pair< string,int>("bread"), 5.0); //insert函数插入pair数据
myrecipe.insert(mypantry.begin(), mypantry.end());  // 范围插入
myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
myrecipe["coffee"] = 10.0;  //数组形式插入
 myrecipe.emplace("apple", 5.0);//构造及插入一个元素 

STL中的map

1.map的简介

map是C++STL中的一个关联式容器,它提供一对一的hash,它类似于Python中的字典,也有着键值对(Key-Value)这一说。我们可以通过键(Key)来找到值(Value),但需要注意的是,每个键(Key)只能在map中出现一次哦!

map可以储存多种类型的数据,它主要用于一对一映射的情况,map内部的实现是通过自建一颗红黑树,这颗树可以对数据进行自动排序。所以在map内部所有的数据都是有序的,这个功能以后可以方便我们解决很多问题。

使用map时需要包含头文件:

#include<map>

2.map的定义及初始化

定义map<数据类型1,数据类型2>变量名
例:

//map的定义 
map<int,int> m1; //定义一个Key数据类型为int,Value数据类型为int的map容器m1 
map<double,double> m2; //定义一个Key数据类型为double,Value数据类型为double的map容器m2 
map<int,string> m3; //定义一个Key数据类型为int,Value数据类型为string的map容器m3

3.迭代器

begin   返回指向容器起始位置的迭代器(iterator) 
end      返回指向容器末尾位置的迭代器 
cbegin    返回指向容器起始位置的常迭代器(const_iterator) 
cend    返回指向容器末尾位置的常迭代器 

代码:

//unordered_map::bucket_count
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<string, string> mymap =
    {  
        {"house", "maison"},      
        {"apple", "pomme"},   
        {"tree", "arbre"},
        {"book", "livre"},
        {"door", "porte"},
        {"grapefruit", "pamplemousse"}
    };
  
    /************begin和end迭代器***************/
    cout << "mymap contains:";
  
    for (auto it = mymap.begin(); it != mymap.end(); ++it)
        cout << " " << it->first << ":" << it->second;
    cout << endl;

    /************bucket操作***************/
    unsigned n = mymap.bucket_count();
    cout << "mymap has " << n << " buckets.\n";
    for (unsigned i = 0; i < n; ++i)
    {
        cout << "bucket #" << i << "'s size:" << mymap.bucket_size(i) << " contains: ";
        for (auto it = mymap.begin(i); it != mymap.end(i); ++it)
             cout << "[" << it->first << ":" << it->second << "] ";
        cout << "\n";
    }
    cout << "\nkey:'apple' is in bucket #" << mymap.bucket("apple") << endl;
    cout << "\nkey:'computer' is in bucket #" << mymap.bucket("computer") << endl;

    return 0;
}

输出:

mymap contains: house:maison apple:pomme tree:arbre book:livre door:porte grapefruit:pamplemousse
mymap has 8 buckets.
bucket #0's size:1 contains: [book:livre]
bucket #1's size:1 contains: [door:porte]
bucket #2's size:1 contains: [grapefruit:pamplemousse]
bucket #3's size:1 contains: [house:maison]
bucket #4's size:0 contains:
bucket #5's size:1 contains: [tree:arbre]
bucket #6's size:0 contains:
bucket #7's size:1 contains: [apple:pomme]

key:'apple' is in bucket #7

key:'computer' is in bucket #0

4.Capacity操作

size     返回有效元素个数 
max_size  返回 unordered_map 支持的最大元素个数 
empty      判断是否为空 

5.元素访问

operator[]       访问元素 
at         访问元素 
#include<iostream>
#include<map>
using namespace std;
int main()
{
	map<int, string> m1;
	m1[1] = "ctx";
	m1[2] = "cxt";
	m1[3] = "txc";
	m1[10] = "txt";
	m1[5] = "666";
	map<int, string>::iterator it;
	for (it = m1.begin(); it != m1.end(); it++)
	{
		cout << it->first << " " << it->second << endl;
	}
	//it->为Key,it->second为Value 

	return 0;
}

输出:

1 ctx
2 cxt
3 txc
5 666
10 txt

6.查找

unordered_map<string, double>::const_iterator got = myrecipe.find("coffee");

if (got == myrecipe.end())
    cout << "not found";
else
    cout << "found " << got->first << " is " << got->second << "\n\n";

7.元素修改

insert    插入元素 
erase   删除元素 
swap    交换内容 
clear     清空内容 
emplace  构造及插入一个元素 
emplace_hint 按提示构造及插入一个元素 

插入:

unordered_map < string, double> myrecipe, mypantry = { {"milk",2.0},{"flour",1.5} };
/****************插入*****************/

pair<string, double> myshopping("baking powder", 0.3);
myrecipe.insert(myshopping);                        // 复制插入
myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // 移动插入
myrecipe.insert(mypantry.begin(), mypantry.end());  // 范围插入
myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
myrecipe["coffee"] = 10.0;  //数组形式插入
 myrecipe.emplace("apple", 5.0);//构造及插入一个元素 

mapStudent.insert(pair<int, string>(1, "student_one")); //insert函数插入pair数据,
mapStudent.insert(map<int, string>::value_type (1, "student_one"));//用insert函数插入value_type数据
mapStudent.insert(make_pair(1, "student_one")); //在insert函数中使用make_pair()函数
mapStudent[1] = "student_one"; //用数组方式插入数据

删除:

myrecipe.erase(myrecipe.begin());  //通过位置
myrecipe.erase("milk");    //通过key
display(myrecipe, "After erase myrecipe contains:");

交换:

myrecipe.swap(mypantry);
display(myrecipe, "After swap with mypantry, myrecipe contains:");

修改:

/****************修改*****************/
myrecipe.at("coffee") = 9.0;
myrecipe["milk"] = 3.0;
display(myrecipe, "After modify myrecipe contains:");

清空:

myrecipe.clear();
display(myrecipe, "After clear, myrecipe contains:");

完整代码:

// unordered_map::insert
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;

void display(unordered_map<string, double> myrecipe, string str)
{
    cout << str << endl;
    for (auto& x : myrecipe)
        cout << x.first << ": " << x.second << endl;
    cout << endl;
}

int main()
{
    unordered_map < string, double> myrecipe, mypantry = { {"milk",2.0},{"flour",1.5} };
    /****************插入*****************/

    pair<string, double> myshopping("baking powder", 0.3);
    myrecipe.insert(myshopping);                        // 复制插入
    myrecipe.insert(make_pair<string, double>("eggs", 6.0)); // 移动插入
    myrecipe.insert(mypantry.begin(), mypantry.end());  // 范围插入
    myrecipe.insert({ {"sugar",0.8},{"salt",0.1} });    // 初始化数组插入(可以用二维一次插入多个元素,也可以用一维插入一个元素)
    myrecipe["coffee"] = 10.0;  //数组形式插入
    myrecipe.emplace("apple", 5.0);

    display(myrecipe, "myrecipe contains:");
    /****************查找*****************/
    unordered_map<string, double>::const_iterator got = myrecipe.find("coffee");

    if (got == myrecipe.end())
        cout << "not found";
    else
        cout << "found " << got->first << " is " << got->second << "\n\n";

    /****************修改*****************/
    myrecipe.at("coffee") = 9.0;
    myrecipe["milk"] = 3.0;
    display(myrecipe, "After modify myrecipe contains:");

    /****************擦除*****************/
    myrecipe.erase(myrecipe.begin());  //通过位置
    myrecipe.erase("milk");    //通过key
    display(myrecipe, "After erase myrecipe contains:");

    /****************交换*****************/
    myrecipe.swap(mypantry);
    display(myrecipe, "After swap with mypantry, myrecipe contains:");

    /****************清空*****************/
    myrecipe.clear();
    display(myrecipe, "After clear, myrecipe contains:");

    return 0;
}

输出:

found coffee is 10

After modify myrecipe contains:
baking powder: 0.3
eggs: 6
flour: 1.5
apple: 5
milk: 3
sugar: 0.8
salt: 0.1
coffee: 9

After erase myrecipe contains:
eggs: 6
flour: 1.5
apple: 5
sugar: 0.8
salt: 0.1
coffee: 9

After swap with mypantry, myrecipe contains:
milk: 2
flour: 1.5

After clear, myrecipe contains:

8.操作

find       通过给定主键查找元素,没找到:返回unordered_map::end
count      返回匹配给定主键的元素的个数 
equal_range   返回值匹配给定搜索值的元素组成的范围 

9.Buckets

bucket_count    返回槽(Bucket)数 
max_bucket_count    返回最大槽数 
bucket_size       返回槽大小 
bucket       返回元素所在槽的序号 
load_factor     返回载入因子,即一个元素槽(Bucket)的最大元素数 
max_load_factor    返回或设置最大载入因子 
rehash       设置槽数 
reserve        请求改变容器容量

参考:[详细介绍C++STL:unordered_map](

标签:myrecipe,map,contains,insert,插入方式,插入,哪几种,pair
From: https://www.cnblogs.com/codemagiciant/p/17602028.html

相关文章

  • 17.STL中unordered_map(hash_map)和map的区别,hash_map如何解决冲突以及扩容
    17.STL中unordered_map(hash_map)和map的区别,hash_map如何解决冲突以及扩容1.区别1.1需要引入的头文件不同map:#include<map>unordered_map:#include<unordered_map>1.2内部实现机理不同map:map内部实现了一个红黑树(红黑树是非严格平衡二叉搜索树,而AVL是严格平衡二......
  • 18.vector越界访问下标,map越界访问下标?vector删除元素时会不会释放空间?
    18.vector越界访问下标,map越界访问下标?vector删除元素时会不会释放空间?1.vector越界访问下标std::vector是C++标准库中的一种动态数组,其大小可以根据需要进行调整。当你试图访问一个不存在的元素,即访问超出其当前大小范围的索引时,将会发生越界访问。在C++中,如果你使用operator[......
  • 19.map中[]与find的区别?
    19.map中[]与find的区别?map的下标运算符[]的作用是:将关键码作为下标去执行查找,并返回对应的值;如果不存在这个关键码,就将一个具有该关键码和值类型的默认值的项插入这个map。map的find函数:用关键码执行查找,找到了返回该位置的迭代器;如果不存在这个关键码,就返回尾迭代器。......
  • 浅谈Map<String, String[]> p=req.getParameterMap();
    这行代码用于获取当前HTTP请求中的所有参数,并将它们存储在一个Map<String,String[]>类型的对象中。解释如下:req:这是一个HttpServletRequest对象,表示当前的HTTP请求。通过它可以获取请求中的参数信息。getParameterMap():这是HttpServletRequest接口的方法,用......
  • MappingJackson2HttpMessageConverter数据处理
    主键用的雪花算法,值域超过了js的范围……后端返回的日期字段总不是我想要的格式……空值的字段就不要返回了,省点流量吧……试试换成自己的MappingJackson2HttpMessageConverter呗Talkischeap,showyouthecode!importcom.fasterxml.jackson.annotation.JsonInclude;importco......
  • freemeker 遍历map嵌套list数据结构
    遍历嵌套数据结构渲染map中value是list的内容<#ifnodes??&&(nodes?size>0)>【节点明细】<#listnodes?keysasalarmLevel>${alarmLevel+":"}<#if(nodes[alarmLevel])??><#list(nodes[alarmLevel])asnode>${node.nodeNo}<#sep>,&......
  • 什么是散列函数?HashMap 的实现原理是什么?
    散列函数(HashFunction)是一种将输入数据(通常是任意大小的数据)映射为固定大小散列值(哈希值)的函数。散列函数的目标是将数据均匀地映射到哈希值域,以便在哈希表等数据结构中高效地查找、插入和删除数据。好的散列函数应该尽可能避免冲突(即不同的输入映射到相同的哈希值),并具有良好的性......
  • weekset和weekmap
     在ES6中,WeakSet和WeakMap是两种特殊的集合数据结构,它们与Set和Map相似,但具有一些不同之处。WeakSet:WeakSet是一种弱引用集合,它只能存储对象,而不能存储原始值(如字符串、数字等)。WeakSet中存储的对象都是弱引用,如果没有其他地方引用这些对象,垃圾回收机制会自动回收......
  • js set和map详解
      当我们需要存储唯一值的集合时,可以使用Set。Set是一种有序的、无重复值的集合,它可以存储任何类型的值,包括原始值和对象。下面是使用Set的示例:Copy//创建一个SetconstmySet=newSet();//添加值mySet.add(1);mySet.add(2);mySet.add(3);//删除值......
  • js weekset和weekmap详解
    在JavaScript中,WeakSet和WeakMap是Set和Map的变体,它们的特点是只能存储对对象的弱引用。这意味着,如果一个对象只被WeakSet或WeakMap引用,而没有被其他地方引用,那么它可能会被垃圾回收器清理掉。这在某些情况下非常有用,比如处理缓存或临时数据等。WeakSet和WeakMap的用法与Set和Map......