Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixed Arrays in C++ and C#

Tags:

c++

arrays

c#

Is it possible to create a Mixed Array in both C++ and C#

I mean an array that contains both chars and ints?

ex:

Array [][] = {{'a',1},{'b',2},{'c',3}};
like image 395
sikas Avatar asked Dec 08 '10 22:12

sikas


2 Answers

Neither C# nor C++ support creating this kind of data structure using native arrays, however you could create a List<Tuple<char,int>> in C# or a std::vector<std::pair<char,int>> in C++.

You could also consider using the Dictionary<> or std::map<> collections if one of the elements can be considered a unique key, and the order of the elements is unimportant but only their association.

For the case of lists (rather than dictionaries), in C# you would write:

List<Tuple<char,int>> items = new List<Tuple<char,int>>();

items.Add( new Tuple<char,int>('a', 1) );
items.Add( new Tuple<char,int>('b', 2) );
items.Add( new Tuple<char,int>('c', 3) );

and in C++ you would write:

std::vector<std::pair<char,int>> items;  // you could typedef std::pair<char,int>
items.push_back( std::pair<char,int>( 'a', 1 ) );
items.push_back( std::pair<char,int>( 'b', 2 ) );
items.push_back( std::pair<char,int>( 'c', 3 ) );
like image 89
LBushkin Avatar answered Sep 24 '22 23:09

LBushkin


In C++ you would have to use something like std::vector<boost::tuple< , , > or std::vector<std::pair> if you only have two elements in each tuple.

Example for the C++ case:

typedef std::pair<int, char> Pair;

std::vector<Pair> pairs;

pairs.push_back(Pair(0, 'c'));
pairs.push_back(Pair(1, 'a'));
pairs.push_back(Pair(42, 'b'));

Extended example for the C++ case (using boost::assign).

using boost::assign;

std::vector<Pair> pairs;

pairs += Pair(0, 'c'), Pair(1, 'a'), Pair(42, 'b');

For C# you may want to see this.

like image 41
Yippie-Ki-Yay Avatar answered Sep 24 '22 23:09

Yippie-Ki-Yay