map<int , vector<int> >

这篇文章展示了如何在C++中使用`map`和`vector`数据结构,通过`main()`函数接收用户输入,计算并输出对应键值的vector大小。
#include <iostream>
#include <vector>
#include <map>
using namespace std;

int main(){
	map<int,vector<int> > mp;
	for(int i=0;i<2;i++){
		int x;cin>>x;
		for(int j=0;j<4;j++){
			mp[x].push_back(j);
		}
	}
	int y=mp[1].size();
	cout<<y;
	return 0;
} 

如果输入1 1,结果返回8,输入1 0结果返回4。

mp[1].size()返回键1所对应的vector的大小,mp[1].push_back(j);将1对应的vectorpush_back了。

mp.size()返回map容器mp里有几个键值对,输入任意两数,返回2。

部分编译器要求vector<int> >俩">"要隔开

 

C++ 中,`std::map<int, std::vector<int>>` 是一种键值对容器,其中键是 `int` 类型,值是 `std::vector<int>` 类型。默认情况下,`std::map` 会根据键(`int`)进行排序。如果需要对键或值进行自定义排序,可以通过将 `map` 的内容复制到一个支持自定义排序的容器(如 `std::vector<std::pair<int, std::vector<int>>>`)中,然后使用 `std::sort` 进行排序。 ### 按键排序 如果需要按照键进行排序,可以直接利用 `std::map` 的特性,因为 `std::map` 默认按键升序排列。 ### 按值排序 如果需要按照值(`std::vector<int>`)进行排序,则需要将 `map` 的内容复制到一个 `std::vector<std::pair<int, std::vector<int>>>` 中,然后通过自定义比较函数或 lambda 表达式进行排序。 以下是一个完整的示例代码,展示了如何对 `std::map<int, std::vector<int>>` 按键和值进行排序: ```cpp #include <iostream> #include <map> #include <vector> #include <algorithm> // 自定义比较函数:按值排序(根据 vector 的大小) bool compareByValue(const std::pair<int, std::vector<int>>& a, const std::pair<int, std::vector<int>>& b) { return a.second.size() < b.second.size(); } int main() { // 初始化 map std::map<int, std::vector<int>> myMap = { {3, {1, 2, 3}}, {1, {4, 5}}, {2, {6}} }; // 将 map 内容复制到 vector 中 std::vector<std::pair<int, std::vector<int>>> vecMap(myMap.begin(), myMap.end()); // 按键排序(默认情况下 map 已排序) std::cout << "Sorted by key:" << std::endl; for (const auto& pair : myMap) { std::cout << pair.first << " => "; for (const auto& val : pair.second) { std::cout << val << " "; } std::cout << std::endl; } // 按值排序(根据 vector 的大小) std::sort(vecMap.begin(), vecMap.end(), compareByValue); std::cout << "\nSorted by value (vector size):" << std::endl; for (const auto& pair : vecMap) { std::cout << pair.first << " => "; for (const auto& val : pair.second) { std::cout << val << " "; } std::cout << std::endl; } return 0; } ``` ### 输出示例 ``` Sorted by key: 1 => 4 5 2 => 6 3 => 1 2 3 Sorted by value (vector size): 2 => 6 1 => 4 5 3 => 1 2 3 ``` - **按键排序**:使用 `std::map` 的默认排序特性,按键升序排列。 - **按值排序**:将 `map` 内容复制到 `std::vector` 中,并使用自定义比较函数 `compareByValue` 对 `vector` 的大小进行排序。 通过这种方式,可以灵活地对 `std::map<int, std::vector<int>>` 进行按键或值排序。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值