【问题标题】:Constructing associative containers构建关联容器
【发布时间】:2010-10-22 09:39:50
【问题描述】:

我确信(直到我刚刚尝试过)可以使用数组样式表示法来实例化关联容器。

例如,

std::set< int > _set = { 2, 3, 5 };

情况并非如此,但我想知道是否还有其他方法可以像这样在构造函数中批量初始化容器?

【问题讨论】:

  • 这在 C++0x 中应该是可能的。由于目前的语言,您无法使用此语法初始化任何容器。
  • std::set 真的是关联容器吗?
  • @FredOverflow:根据sgi documentation,它是一个排序的关联容器。
  • @FredOverflow:你有什么疑问?
  • @Arun:我一直认为关联容器提供了从键到元素的映射,例如std::map&lt;K, V&gt;(每个键都与其值关联)。跨度>

标签: c++ stl constructor containers associative


【解决方案1】:

您可以使用Boost.Assign

std::set< int > _set = boost::assign::list_of(2)(3)(5);

【讨论】:

    【解决方案2】:

    你可以这样做:

    const int x[] = { 2, 3, 5 };
    std::set<int> _set(&x[0], &x[sizeof(x)/sizeof(x[0])]);
    

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多