【问题标题】:Mixed Arrays in C++ and C#C++ 和 C# 中的混合数组
【发布时间】:2010-12-08 22:29:55
【问题描述】:

是否可以在 C++ 和 C# 中创建混合数组

我的意思是一个包含字符和整数的数组?

例如:

Array [][] = {{'a',1},{'b',2},{'c',3}};

【问题讨论】:

  • char 是 C++ 中的整数类型

标签: c# c++ arrays


【解决方案1】:

C# 和 C++ 都不支持使用原生数组创建这种数据结构,但是您可以在 C# 中创建 List<Tuple<char,int>> 或在 C++ 中创建 std::vector<std::pair<char,int>>

如果元素之一可以被视为唯一键,并且元素的顺序并不重要,而只是它们的关联关系,您也可以考虑使用 Dictionary<>std::map<> 集合。

对于列表(而不是字典),在 C# 中你会这样写:

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

在 C++ 中你会这样写:

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

【讨论】:

  • 而不是 std::pair( 'a', 1 ) 你可以只使用 std::make_pair('a', 1),stdlib 为您提供方便: )
  • 为什么他不能创建一个pairs/tuples数组?有什么原因我看不到他唯一的选择是切换到 List/vector 吗?
  • @jalf STL 驱动的容器可能比通用数组更不容易出错。
  • 是的。我只是指出,OP 问题的“最小”解决方案是使用元组/对。更改容器类型与问题无关,是否更安全。我只是认为,如果一个答案改变了前提,它应该有充分的理由这样做,并解释清楚。
【解决方案2】:

C++ 中,如果每个元组中只有两个元素,则必须使用std::vector&lt;boost::tuple&lt; , , &gt;std::vector&lt;std::pair&gt; 之类的内容。

C++ 案例的示例:

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

C++ 案例的扩展示例(使用 boost::assign)。

using boost::assign;

std::vector<Pair> pairs;

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

对于C#,您可能想查看this.

【讨论】:

  • 你能举例说明如何实现这一点吗?
  • std::vector<:pair> 首选
【解决方案3】:

在 C# 和 C++ 中,无法创建混合类型的数组。您应该使用其他类,例如 C++ 中的 std::vector 或 C# 中的 Dictionary

【讨论】:

    【解决方案4】:

    经典数组(带括号的数组)只能有一种类型,这是其声明的一部分(如 int[] nums)。没有数组[]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多