user3168101
user3168101

Reputation: 13

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

I have to develop stl map in which key is integer where value associated with key is 5 tuple. having integer data types only.

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

and so on. how i can implement it for insert and search operation.

mean how to map single key value to tuple of 5 values. how to accomplish it?

Upvotes: 0

Views: 146

Answers (2)

wesley.mesquita
wesley.mesquita

Reputation: 785

If you have access to C++11, you can make use of std::tuple (or boost´s tuple), which I believe is the best fit data structure to your case. See the snippet below and see if it fits:

#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;
}

Executing this snippet you must get:

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

Upvotes: 1

sigy
sigy

Reputation: 2500

Depending on what your data means I would go for a different approach. If your values logically belong together, that is if they only make sense in combination, then I would simply store them in a common data structure and store this data structure in a map. For this purpose a class, struct or container might suit your needs. Again it depends on your context what is the best choice. If your values exist in isolation and the only connection between them is that they share the same key, then I would use std::multimap.

Upvotes: 1

Related Questions