Gabe
Gabe

Reputation: 95

Container of 2 Types

Is there any C++ container that can store 2 (or more) types of values, such as ints and chars? I want to make a blackjack game. The deck has to consist of both ints and chars. I don't want to initialize it with just numbers (so don't say anything about that!). I am a very beginner programmer, so don't make it too complicated.

Upvotes: 2

Views: 493

Answers (6)

Xeo
Xeo

Reputation: 131907

Since you're a beginner, just use the basic stuff: a struct.

#include <vector>
#include <iostream>

struct MyStruct{
  char cval;
  int ival;
};

int main(){
  using namespace std;

  vector<MyStruct> myvec;
  MyStruct values;

  values.cval = 'S';
  values.ival = 42;
  myvec.push_back(values);

  values.cval = 'A';
  values.ival = 1337;
  myvec.push_back(values);

  values.cval = 'X';
  values.ival = 314159;
  myvec.push_back(values);

  for(int i=0; i < myvec.size(); ++i)
    cout << "myvec[" << i << "], cval: " << myvec[i].cval << ", ival: " << myvec[i].ival << "\n";
}

Output:

myvec[0], cval: S, ival: 42  
myvec[1], cval: A, ival: 1337  
myvec[2], cval: X, ival: 314159  

You can see the output live on Ideone.

Upvotes: 2

Tam&#225;s
Tam&#225;s

Reputation: 48101

I'm assuming that you need a container which is able to store either ints or chars.

First, take a look at the boost::any datatype in Boost, that might help. You can then create a container of boost::any instances.

If you don't want to use boost or it seems overkill, use a union as follows:

typedef struct {
    char type;
    union {
        char character;
        int integer;
    };
} my_struct;

The contents of the character and the integer field in the union then occupy the same memory slots. (Well, the integer uses more slots since chars are usually only one byte). It is then up to you to set the type field of the struct to, say, 'c' if you store a character and to, say, 'i' to store an integer, and then access the contents of the struct using the character or the integer field depending on the value of type.

Finally, there's also the QVariant datatype of Qt, which works similarly to the second approach described above.

Upvotes: 6

Skyler Saleh
Skyler Saleh

Reputation: 3991

If you want to use all of the values simultaneously, you can use something like this...

std::pair<int,char> twovals;
std::pair<int,std::pair<char,float> > threevals;

Upvotes: 2

Adrian
Adrian

Reputation: 20078

Also you can use Boost.Variant

Upvotes: 3

scdmb
scdmb

Reputation: 15641

You can use Boost Tuple objects. More info : http://www.boost.org/doc/libs/1_46_1/libs/tuple/doc/tuple_users_guide.html#using_library

Upvotes: 0

Trent
Trent

Reputation: 13497

Use a struct, class, or std::pair to group the different types into a composite type and then use the appropriate STL container.

Upvotes: 0

Related Questions