对于multimap,它是一个可以拥有重复key值的数据结构,当进行相应地查找时,需要使用迭代器来存放寻找到的key对应的所有value,同时可以进行相应的删除。
在删除时,很容易出现一些错误 (之前写项目遇到了这方面的坑),现在来介绍删除的正确方式。
当然 代码中也将 map的建立,遍历加入了进来
下面直接上代码:
//
// main.cpp
//
// Created by Qiucheng LIN on 2019/10/11.
// Copyright © 2019 Qiucheng LIN. All rights reserved.
//
#include <iostream>
#include<map>
typedef struct insert
{
int ID;
char name[20];
}insert;
int main()
{
/*建表*/
std::multimap<int,insert> Table;
insert in1;
insert in2;
insert in3;
insert in4;
insert in5;
insert in6;
in1.ID=20;
strcpy(in1.name, "james");
in2.ID=21;
strcpy(in2.name, "wade");
in3.ID=22;
strcpy(in3.name, "kobe");
in4.ID=23;
strcpy(in4.name, "james");
in5.ID=24;
strcpy(in5.name, "james");
in6.ID=25;
strcpy(in6.name, "tmac");
/* 插入元素 */
Table.insert(std::pair< int, insert>(1,in1));
Table.insert(std::pair< int, insert>(1,in2));
Table.insert(std::pair< int, insert>(1,in3));
Table.insert(std::pair< int, insert>(1,in4));
Table.insert(std::pair< int, insert>(2,in5));
Table.insert(std::pair< int, insert>(2,in6));
/*遍历输出*/
std::cout<<"Table is:"<<std::endl;
for(std::multimap<int, insert>::iterator itr = Table.begin(); itr != Table.end(); itr++){
std::cout<<"key="<<itr->first<<" ID="<<itr->second.ID<<" name="<<itr->second.name<<std::endl;
}
std::cout<<std::endl<<std::endl;
/*查找 key值为1的value,并且删除名字叫 james的人*/
std::cout<<"There are "<<Table.count(1)<<" peoples key is 1"<<std::endl; //输出key为1的人数
typedef std::multimap<int,insert>::iterator multimap_iterator; // 为了方便使用,typedef一下迭代器定义
std::pair<multimap_iterator,multimap_iterator> it =
Table.equal_range(1); //使用迭代器找出key为1的所有结果
while(it.first!=it.second){ //查找
if(strcmp(it.first->second.name,"james")==0){
std::cout<<"Delete ID="<<it.first->second.ID<<" name="<<it.first->second.name<<std::endl;
it.first=Table.erase(it.first);
continue; //这一步很重要,删除完之后 不要 it.first++
}
it.first++;
}
/*再次遍历输出查看删除效果*/
std::cout<<"\n\nShow Table again\n";
for(std::multimap<int, insert>::iterator itr = Table.begin(); itr != Table.end(); itr++){
std::cout<<"key="<<itr->first<<" ID="<<itr->second.ID<<" name="<<itr->second.name<<std::endl;
}
}
可以看到如下输出结果:
Table is:
key=1 ID=20 name=james
key=1 ID=21 name=wade
key=1 ID=22 name=kobe
key=1 ID=23 name=james
key=2 ID=24 name=james
key=2 ID=25 name=tmac
There are 4 peoples key is 1
Delete ID=20 name=james
Delete ID=23 name=james
Show Table again
key=1 ID=21 name=wade
key=1 ID=22 name=kobe
key=2 ID=24 name=james
key=2 ID=25 name=tmac
Program ended with exit code: 0

本文详细介绍如何在C++中正确使用multimap数据结构,包括插入、遍历和删除操作,特别关注删除具有特定属性的元素的过程。通过具体示例,展示了如何避免常见错误并实现高效的数据管理。
1610

被折叠的 条评论
为什么被折叠?



