具有多个值的无序列图
Unordered map with multiple values
本文关键字:无序 更新时间:2023-10-16
所以我有一个无序映射,对于每个键,我想存储两个唯一的浮点数。这些浮点数表示我正在模拟的东西随时间推移的聚合值,因此随着我的代码的进展,可以添加现有键的值,并且可以创建新键。
以前我只跟踪一个值,因此无序图是简单的解决方案。我不确定如何用一个键保存两个不同的值?
- 使用
unordered_map<int,vector<float> >
是我的第一个想法,但随后添加到现有值并不容易。似乎我必须首先确定密钥是否存在,然后将新向量分量添加到现有向量中,或者将键设置为与新向量相等。 - 我看着unordered_multimap。虽然我对它的工作原理没有很好的感觉,但它似乎并没有提供跟踪哪些值是哪个值的好方法,因为我有两个值,我想将它们分开并能够确定哪个是哪个。
有没有其他方法可以解决这个问题?
使用unordered_map<int,pair<float,float> >
是一个简单的解决方案。
您可以使用unordered_map< int, std::pair< float, float > >
,通过对的.first
和.second
函数访问值。 不过,我不确定这是否比使用vector< float >
方法"更容易"。 向量方法的优点是允许您扩展以轻松存储更多值。 pair
方法的优点是显式地是两个值,并且只有两个值。
如上所述,
您可以使用vector
和pair
。如果值数是固定的,您还可以考虑创建struct
。当单个记录中具有来自多个数据类型的多个值时,这可能更容易。
struct Data {
float value1;
float value2;
};
unordered_map<int, Data> myMap;
您可以使用可变长度的元组
#include<iostream>
#include <iterator>
#include<map>
#include <string>
#include <vector>
using namespace std;
int main()
{
// Defining Map with two two values
map <string, tuple<int, int>> g1;
g1.insert({"camera1", make_tuple(10,20)});
g1.insert({"camera2", make_tuple(100,208)});
g1.insert({"camera3", make_tuple(1000,202)});
g1.insert({"camera4", make_tuple(102,202)});
g1.insert({"camera5", make_tuple(104,203)});
g1.insert({"camera6", make_tuple(109,203)});
//print map g1
cout<<"nThe map g1 is : n";
cout <<"n KeytElement n";
string val = "camera7";
// // Find the specific key is present if not add that
map<string,tuple<int, int>>::iterator itr;
itr = g1.find("camera7");
if(itr ==g1.end())
{
cout << "Key-value pair not present in map n" ;
g1.insert({val, make_tuple(200,192)});
}
else
{ cout<<itr->first;
cout<<"x: "<< get<0>((itr->second));
cout<<"y: "<< get<1>((itr->second));
}
// //updated value
cout<<"Updated Valuen";
cout <<"n tKeyttElement1tElement2 n";
for (itr=g1.begin(); itr!=g1.end();itr++)
{
cout<<"t"<<itr->first<<"t"<< get<0>(itr->second)<< " tt"<<get<1>(itr->second)<<"n";
}
cout<<endl;
return 0;
}
相关文章:
- 递归无序映射
- c++找不到具有相同哈希的无序集合元素
- 正在将无序映射设置为无序映射的值
- 智能指针作为无序映射键,并通过引用进行比较
- 如何使用set实现无序数据结构?
- 如何写向量的无序向量集,即unordered_set<向量<向量<int>>集合?
- 如何禁用 CPU 的无序执行
- 从C++无序集合中高效提取元素
- 打印无序映射的第二个元素,即集合
- 当我将其插入无序地图时,矢量的容量为 0
- 代码块中无序多集的编译错误17.12
- 由并发无序映射查找线程调用的函数是否安全?
- 如何按值对无序哈希映射进行排序
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 使用无序映射在STL中存储键值对
- 为C++中的无序映射获取给定输入键的错误值
- 如何将一个单词拆分成字母,并将它们放入一个无序的列表/集合中
- 将大型对象存储在无序映射中是否效率低下
- 仅从无序集合中删除一个项目