Mixed Arrays in C++ and C#

前端 未结 4 391
心在旅途
心在旅途 2021-01-03 03:21

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         


        
相关标签:
4条回答
  • 2021-01-03 03:53

    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 ) );
    
    0 讨论(0)
  • 2021-01-03 03:54

    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.

    0 讨论(0)
  • 2021-01-03 03:54

    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#.

    0 讨论(0)
  • 2021-01-03 04:12

    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 讨论(0)
提交回复
热议问题