Baz
Baz

Reputation: 13135

Storing a set of arrays of different types

As a matter of interest, lets say I have the following class:

class Data
{
public:
    template<class T>
    std::vector<T> getData(std::string& dataName);
private:
    ...
}:

So the class stores a set of vectors of any type. Each vector has a name and I know its type when retrieving it. What container might I use to store this data within the Data class? A std::vector<std::pair<std::string,std::vector<T>>>?

UPDATE:

I will also need to iterate over this class and the items must be in the same orders as I added them.

For example, I might have:

ownerNames: std::vector<std::string>;
ipAddress: std::vector<char>;

in my store. So when I iterate I need them in this order.

Upvotes: 0

Views: 210

Answers (3)

Kerrek SB
Kerrek SB

Reputation: 477120

If you know the type upon retrieval, use a boost::any:

struct Data
{
    std::map<std::string, boost::any> store;

    template <typename T>
    std::vector<T> & get(std::string const & s)
    {
        boost::any & a = store.find(s)->second;       // check existence!
        return boost::any_cast<std::vector<T> &>(a);  // try/catch bad cast!
    }

    template <typename T>
    bool put(std::string const & s, std::vector<T> v)
    {
        return store.emplace(s, std::move(v)).second;
    }
};

Usage:

void f(Data & d)
{
    try
    {
        auto & v = d.get<int>("MyNumbers");
    }
    catch (boost::bad_any_cast const & e)
    {
        std::cout << "'MyNumbers' is not an int-vector.\n";
    }
}

Upvotes: 3

Skizz
Skizz

Reputation: 71070

OK, based on the latest comment, I suggest a class like this:-

class Server
{
public:
  const IPAddress GetIPAddress ();
  vector <std::string> &GetOwners ();
};

where IPAddress is a helper class to store an IP address and access it in various ways (four chars, string, int, etc...).

I really wouldn't try to force the same access style onto the two different data collections (IP address, owner names).

Upvotes: -1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361482

I think you want boost::any.

typedef std::vector<boost::any> any_vector;

std::map<std::string, any_vector> data;

Upvotes: 3

Related Questions