映射容器-map

映射容器-map


一、目的

-掌握时间复杂度
-掌握map的用法
-掌握substr用法

二、实验内容与设计思想

函数相关伪代码

1.map<string,string>m,n
2.while(getline(cin,total)),遇空行结束
3.循环输入key和value
4.使用m.find()或n.find()来寻找
5.用vector来存储,最后排序

函数代码

#include<iostream>
#include<map>
#include<string>
#include<vector>
#include <algorithm>
using namespace std;
bool compare(string a, string b) {
	return a < b;
}
int main()
{
	map<string, string> m;
	map<string, string> n;
	string key, value,total,find;
	vector<string>number,value1;
	int s,i=0;
	while (getline(cin, total))
	{
		if (total.empty())
			break;
		s = total.find(" ");
		key = total.substr(0, s);
		value = total.substr(s + 1);
		if (m.find(key) == m.end()) {//(m.count(key) <=0/==0)
			m[key] = value;
			n[value] = key;     
			number.push_back(key);
			value1.push_back(value);
		}
		else {
			cout << "此key已经被使用" << endl;
		}
	}
	getline(cin, find);
	if (m.find(find) != m.end()) {
		cout << m[find] << endl;
	}
	else if (n.find(find) != n.end()) {
		cout << n[find] << endl;
	}
	else {
		cout << "没有找到" << endl;
	}
	cout << "按key排序" << endl;
	sort(number.begin(), number.end());
	for (i = 0; i < number.size(); i++) {
		cout << number[i] << " " << m[number[i]] << endl;
	}
	cout << "按value排序" << endl;
	sort(value1.begin(), value1.end(), compare);
	for (i = 0; i < value1.size(); i++) {
		cout << n[value1[i]] << " " << value1[i] << endl;
	}
	return 0;
}

三、实验使用环境

以下请根据实际情况编写

  • 操作系统:Windows 11专业版
  • 编程语言:C++
  • 开发工具:[Visual studio 2022]

四、实验步骤和调试过程

映射容器

本机运行截图


五、实验小结

遇到的问题及解决方法:

  1. 问题:行的分段
  • 解决方法:修改代码,实现功能

实验体会和收获:

输入处理的时间复杂度为O(n×(k+logn)),其中k表示输入k行,查找阶段为O(logn),最后输出全部的时间复杂度为O(nlogn),总体时间复杂度为O(nlogn).
posted @ 2025-04-20 20:50  穗和  阅读(20)  评论(0)    收藏  举报