草庐IT

map函数

爱康代码 2024-07-16 原文

3.9 map/ multimap容器


3.9.1 map基本概念


简介:
●map中所有元素都是pair
●pair中第一 个元素为key (键值),起到索引作用,第二个元素为value (实值)
●所有元素都会根据元素的键值自动排序
本质:
●map/multimap属于关联式容器, 底层结构是用二二叉树实现。
优点:
●可以根据key值快速找到value值
mab和mulimap区别:
●map不允许容器中有重复key值元素
●multimap允许容器中有重复key值元素


3.9.2 map构造和赋值

 功能描述:
●对map容器进行构造和赋值操作
函数原型: .
构造:

 

 示例:

#include <iostream>
#include <map>
using namespace std;

void printmap(map<int,int>&m)
{
	for (map<int,int>::iterator it = m.begin(); it != m.end(); it++)
		cout <<"key=" << (*it).first <<"value=" << it->second << endl;
	cout << endl;
}
void test()
{   //创建map容器
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(4, 30));
	m.insert(pair<int, int>(3, 40));

	printmap(m);

	//拷贝构造
	map<int, int>m2(m);
	printmap(m2);

	//赋值
	map<int, int>m3;
	m3 = m;
	printmap(m3);

}
int main()
{
	test();
	return 0;
}

总结: map中所有元素都是成对出现,插入数据时候要使用对组
 

3.9.3 map大小和交换

功能描述: .
●统计map容器大小以及交换map容器
函数原型:

示例:

#include <iostream>
#include <map>
using namespace std;

void printmap(map<int,int>&m)
{
	for (map<int,int>::iterator it = m.begin(); it != m.end(); it++)
		cout <<"key=" << (*it).first <<"value=" << it->second << endl;
	cout << endl;
}
void test()
{   //创建map容器
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(4, 30));
	m.insert(pair<int, int>(3, 40));

	if (m.empty())
	{
		cout << "m为空" << endl;
	}
	else
	{
		cout << "m不为空" << endl;
		cout << "m的大小为:" << m.size() << endl;
	}

}
//交换
void test02()
{
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(3, 30));

	map<int, int>m2;
	m2.insert(pair<int, int>(4, 40));
	m2.insert(pair<int, int>(5, 50));
	m2.insert(pair<int, int>(6, 60));

	cout << "交换前:" <<endl;
	printmap(m);
	printmap(m2);

	m.swap(m2);
	cout << "交换后:" << endl;
	printmap(m);
	printmap(m2);

}
int main()
{
	test02();
	return 0;
}

 总结:
.统计大小- size
●判断是否为空--- empty
●交换容器- swap

回3.9.4 map插入和删除


功能描述:
●map容器进行插入数据和删除数据
函数原型:

示例:

#include <iostream>
#include <map>
using namespace std;

void printmap(map<int,int>&m)
{
	for (map<int,int>::iterator it = m.begin(); it != m.end(); it++)
		cout <<"key=" << (*it).first <<"value=" << it->second << endl;
	cout << endl;
}
void test()
{   //创建map容器
	map<int, int>m;
	//插入,第一种
	m.insert(pair<int, int>(1, 10));
	//第二种
	m.insert(make_pair(2, 20));//常用
	//第三种
	m.insert(map<int, int>::value_type(3, 30));
	//第四种
	m[4] = 40;

	//[]不建议去插数,可以利用key访问到value
	//cout << m[4] << endl;
	printmap(m);

	//删除
	m.erase(m.begin());
	printmap(m);

	m.erase(3);//按照key删除
	printmap(m);

	//清空
	//m.erase(m.begin(), m.end());
	m.clear();
	printmap(m);

}
int main()
{
	test();
	return 0;
}

总结:
map插入方式很多,记住其王即可
●插入--- insert
.删除---erase
.清空--- clear

3.9.5 map查找和统计


功能描述:
●对map容器进行查找数据以及统计数据
函数原型:


示例:

#include <iostream>
#include <map>
using namespace std;

void printmap(map<int,int>&m)
{
	for (map<int,int>::iterator it = m.begin(); it != m.end(); it++)
		cout <<"key=" << (*it).first <<"value=" << it->second << endl;
	cout << endl;
}
void test()
{  //查找
	map<int, int>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(4, 30));
	m.insert(pair<int, int>(3, 40));

	map<int, int>::iterator pos = m.find(3);

	if (pos != m.end())
	{
		cout << "查到了元素:" << (*pos).first << "value=" << pos->second << endl;
	}
	else
	{
		cout << "未查元素:" << endl;
	}
	//统计
	//map不允许插入重复的key,count结果要么0要么1;
	//multimap统计可能大于1;
	int num = m.count(3);
	cout << "num=" << num << endl;
}
int main()
{
	test();
	return 0;
}


总结:
●查找一
- find
(返回的是迭代器)
●统计--- count (对于map,结果为0或者1)

 

回3.9.6 map容器排序


学习目标: .
●map容器默认排序规则为按照key值进行从小到大排序,掌握如何改变排序规则
主要技术点:
■利用仿函数,可以改变排序规则

示例:

#include <iostream>
#include <map>
using namespace std;
class  cmp
{
public:
	bool operator()(int  v1, int  v2)
	{
		//降序
		return v1 > v2;
	}
};

void printmap(map<int,int>&m)
{
	for (map<int,int>::iterator it = m.begin(); it != m.end(); it++)
		cout <<"key=" << (*it).first <<"value=" << it->second << endl;
	cout << endl;
}
void test()
{  //查找
	map<int, int,cmp>m;
	m.insert(pair<int, int>(1, 10));
	m.insert(pair<int, int>(2, 20));
	m.insert(pair<int, int>(4, 30));
	m.insert(pair<int, int>(3, 40));
	m.insert(pair<int, int>(5, 50));

	
}
int main()
{
	test();
	return 0;
}



 

有关map函数的更多相关文章

  1. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  2. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

  3. ruby - 在 Ruby 中有条件地定义函数 - 2

    我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin

  4. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  5. C51单片机——实现用独立按键控制LED亮灭(调用函数篇) - 2

    说在前面这部分我本来是合为一篇来写的,因为目的是一样的,都是通过独立按键来控制LED闪灭本质上是起到开关的作用,即调用函数和中断函数。但是写一篇太累了,我还是决定分为两篇写,这篇是调用函数篇。在本篇中你主要看到这些东西!!!1.调用函数的方法(主要讲语法和格式)2.独立按键如何控制LED亮灭3.程序中的一些细节(软件消抖等)1.调用函数的方法思路还是比较清晰地,就是通过按下按键来控制LED闪灭,即每按下一次,LED取反一次。重要的是,把按键与LED联系在一起。我打算用K1来作为开关,看了一下开发板原理图,K1连接的是单片机的P31口,当按下K1时,P31是与GND相连的,也就是说,当我按下去时

  6. ruby-on-rails - 将字符串转换为 ruby​​-on-rails 中的函数 - 2

    我需要一个通过输入字符串进行计算的方法,像这样function="(a/b)*100"a=25b=50function.something>>50有什么方法吗? 最佳答案 您可以使用instance_eval:function="(a/b)*100"a=25.0b=50instance_evalfunction#=>50.0请注意,使用eval本质上是不安全的,尤其是当您使用外部输入时,因为它可能包含注入(inject)的恶意代码。另请注意,a设置为25.0而不是25,因为如果它是整数a/b将导致0(整数)。

  7. ruby - 在 ruby​​ 中使用 .try 函数和 .map 函数 - 2

    我需要从json记录中获取一些值并像下面这样提取curr_json_doc['title']['genre'].map{|s|s['name']}.join(',')但对于某些记录,curr_json_doc['title']['genre']可以为空。所以我想对map和join()使用try函数。我试过如下curr_json_doc['title']['genre'].try(:map,{|s|s['name']}).try(:join,(','))但是没用。 最佳答案 你没有正确传递block。block被传递给参数括号外的方法

  8. ruby - 是否可以从也在该模块中的类内部调用模块函数 - 2

    在这段Ruby代码中:ModuleMClassC当我尝试运行时出现“'M:Module'的未定义方法'helper'”错误c=M::C.new("world")c.work但直接从另一个类调用M::helper("world")工作正常。类不能调用在定义它们的同一模块中定义的模块函数吗?除了将类移出模块外,还有其他解决方法吗? 最佳答案 为了调用M::helper,你需要将它定义为defself.helper;结束为了进行比较,请查看以下修改后的代码段中的helper和helper2moduleMclassC

  9. ruby - 将运算符传递给函数? - 2

    也许这听起来很荒谬,但我想知道这对Ruby是否可行?基本上我有一个功能...defadda,bc=a+breturncend我希望能够将“+”或其他运算符(例如“-”)传递给函数,这样它就类似于...defsuma,b,operatorc=aoperatorbreturncend这可能吗? 最佳答案 两种可能性:以方法/算子名作为符号:defsuma,b,operatora.send(operator,b)endsum42,23,:+或者更通用的解决方案:采取一个block:defsuma,byielda,bendsum42,23,

  10. ruby - 我可以在 Ruby 1.9.x 中使用无参数函数吗? - 2

    所以我正在研究RubyKoans,而且我遇到了一个我认为是ruby1.9.x特有的问题。deftest_calling_global_methods_without_parenthesesresult=my_global_method2,3assert_equal5,resultend我明白了:james@tristan:~/code/ruby_projects/ruby_koans$rake(in/home/james/code/ruby_projects/ruby_koans)cdkoans/home/james/.rvm/rubies/ruby-1.9.2-p180/bin/ru

随机推荐