C++: 使用map迭代器的输入

C++: 使用map迭代器的输入

(第一次写博客,记录一下找遍全网也没弄明白的一个迭代)

多项式加法
【问题描述】
一个多项式可以表示为一组数对,数对中第一个数始终为整数,且唯一,表示多项式的次数,另一数表示为对应的系数且不为0。输入两组数对,每组以0 0作为结束,实现对两个多项式的加法并按降幂输出结果数对
【输入形式】
每行输入一个数对,以空格为分隔符,以0 0结束
【输出形式】
每行输出一个数对,以空格为分隔符
【样例输入】

5 12
3 8
1 2
15 5
0 10
0 0
3 12
30 1
15 5
0 0

【样例输出】

30 1
15 10
5 12
3 20
1 2
0 10

代码实现(已成功)

#include<iostream>
#include<vector>
#include<map>
using namespace std;
int main()
{
	int a,b,s=0;
	map<int,int> poly;
	while(s<2)
	{
		cin>>a>>b;
//		map<int,int>::iterator it=poly.insert(poly.begin(),make_pair(a,0));
		map<int,int>::iterator it=poly.insert(poly.begin(),pair<int,int>(a,0));
		it->second +=b;
		if(a==0&&b==0)
		{
			s++;
		}
	}
	for(map<int,int>::reverse_iterator it=poly.rbegin();it!=poly.rend();it++)
	if(it->second!=0)cout<<it->first<<' '<<it->second<<endl;
	return 0;
}

但笔者基础太差,中间有一句

map<int,int>::iterator it=poly.insert(poly.begin(),pair<int,int>(a,0));

试着改成

map<int,int>::iterator it=poly.begin();
poly.insert(it,pair<int,int>(a,0));
it++;

这样插入好像少了一些值,另外map用insert插值的时候,若key相同不是会报错吗?为什么在这里好像没啥大问题、
高手请留言hahahaha

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ std::map迭代器是用来遍历map容器中的元素的工具。迭代器可以指向map容器中的每个键值对,允许访问键和值。在C++中,有三种常用的迭代器类型:基础迭代器、反向迭代器和常量迭代器。 基础迭代器是通过`begin()`和`end()`函数来获取的。`begin()`函数返回指向map容器中第一个元素的迭代器,而`end()`函数返回指向map容器中最后一个元素之后位置的迭代器。基础迭代器可以使用自增运算符`++`来遍历map容器中的键值对,并通过解引用(*)操作符来获得键和值。例如,使用`map<string, int>::iterator`类型定义迭代器,并通过循环遍历map容器中的键值对,可以实现对map容器的遍历。 反向迭代器是通过`rbegin()`和`rend()`函数来获取的。`rbegin()`函数返回指向map容器中最后一个元素的迭代器,而`rend()`函数返回指向map容器中第一个元素之前位置的迭代器。反向迭代器可以使用自减运算符`--`来遍历map容器中的键值对,并通过解引用(*)操作符来获得键和值。反向迭代器可以实现对map容器的反向遍历。 常量迭代器是通过`cbegin()`和`cend()`函数来获取的。常量迭代器与基础迭代器类似,但是不能修改map容器中的元素。常量迭代器可以用于在不改变map容器的情况下遍历元素。 综上所述,C++ std::map迭代器是用于遍历map容器中的键值对的工具。基础迭代器、反向迭代器和常量迭代器分别用于正向遍历、反向遍历和只读遍历map容器。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C++ std::map迭代器遍历删除遇到的坑](https://blog.csdn.net/zidian666/article/details/125673395)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [C++map迭代器最全最容易理解](https://blog.csdn.net/qq_53547805/article/details/122146122)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值