开发者

Mixed Arrays in C++ and 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}};


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 ) );


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.


In C# and C++ it's not possible to create an array of mixed types. You should use other classes like std::vector in C++ or Dictionary <char, int> in C#.


A classic array (the one with the brackets) can only have one type, which is part of its declaration (like int[] nums). There is no Array[].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜