使用值类在C 中实现STL MAP

Implementation of stl map in c++ using class of values

本文关键字:实现 STL MAP      更新时间:2023-10-16

我必须开发stl映射,其中键是整数,其中与键关联的值是5个元组。仅具有整数数据类型。

e.g key=1
value=(2,3,4,5,6)
key=2
value=(1,2,3,4,5)

等等。我如何实现它以插入和搜索操作。

是指如何将单键值映射到5个值的元组。如何完成?

取决于您的数据含义,我会选择其他方法。如果您的值在逻辑上属于合并在一起,那就是它们仅在组合中有意义,那么我只需将它们存储在通用的数据结构中,然后将此数据结构存储在地图中。为此,课程,结构或容器可能适合您的需求。同样,这取决于您的上下文,什么是最佳选择。如果您的值孤立存在,并且它们之间的唯一连接是它们共享相同的密钥,那么我将使用std :: Multimap。

如果您可以访问C++11,则可以使用std::tuple(或Boost tuple),我相信这是您案例的最佳拟合数据结构。请参阅下面的摘要,看看是否适合:

#include<tuple>
#include<map>
#include<iostream>
#include<stdexcept>
typedef std::tuple<int, int, int, int, int > fiveIntTuple; 
void insert(std::map<int,  fiveIntTuple>& values,  
            int key, int a, int b, int c, int d, int e){
    values[key] = std::make_tuple(a,b,c,d,e);
}
fiveIntTuple search(const std::map<int, fiveIntTuple >& values, int key ){
    return values.at(key);
}
void print(const std::map<int, fiveIntTuple >& values, int key){
    try{
        fiveIntTuple t;
        t = search(values, key);
        std::cout << "For key  == " << key << " got:  " 
        << std::get<0>(t) << "," 
        << std::get<1>(t) << "," 
        << std::get<2>(t) << "," 
        << std::get<3>(t) << "," 
        << std::get<4>(t) << std::endl;         
    }catch(const std::out_of_range&){
        std::cerr << "For key " << key << " ... not found" << std::endl; 
    }
}
int main(){
    std::map<int, fiveIntTuple > my_values;
    insert(my_values, 1, 2,3,4,5,6);
    insert(my_values, 2, 1,2,3,4,5);
    print(my_values, 1);
    print(my_values, 2);
    print(my_values, 3);
    return 0;
}

执行此片段,您必须得到:

For key  == 1 got:  2,3,4,5,6
For key  == 2 got:  1,2,3,4,5
For key 3 ... not found