具有多个值的无序列图

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方法的优点是显式地是两个值,并且只有两个值。

如上所述,

您可以使用vectorpair。如果值数是固定的,您还可以考虑创建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;
}