代码之家  ›  专栏  ›  技术社区  ›  Amir Rachum

是否有快速创建集合的方法?

  •  8
  • Amir Rachum  · 技术社区  · 14 年前

    目前我正在创建这样的新集合:

        std::set<A> s;
        s.insert(a1);
        s.insert(a2);
        s.insert(a3);
        ...
        s.insert(a10);
    

    有办法创造 s 一条线?

    6 回复  |  直到 9 年前
        1
  •  8
  •   icecrime    14 年前

    你可以看看 Boost.Assign ,允许您编写以下内容:

    const std::list<int> primes = boost::assign::list_of(2)(3)(5)(7)(11);
    
        2
  •  17
  •   Moo-Juice    14 年前
    int myints[]= {10,20,30,40,50};
    std::set<int> mySet(myints, myints + 5);
    

    好吧,诚然有两行:)

        3
  •  6
  •   Matthieu M.    9 年前

    在C++0X中,标准定义了 Initializer List 作为这种(笨拙)结构的改进。

    现在更容易了:

    std::set<int> set = {10, 20, 30, 40, 50};
    

    标准库只需声明集合的以下构造函数:

    template <typename Value, typename Compare, typename Allocator>
    set<Value, Compare, Allocator>::set(std::initializer_list<Value> list);
    

    我们所有的忧虑都被一扫而光了。

        4
  •  4
  •   Stuart Golodetz    14 年前
        5
  •  4
  •   Mihran Hovsepyan    14 年前

    如果初始数据在某个容器中 std::some_container<A> a; 它有begin和end迭代器,这是forward迭代器或best迭代器(它们只是应该重载operator++),然后您可以用这种方式创建新的集合。

    std::set<A> s(a.begin(), a.end());
    
        6
  •  3
  •   Steve Townsend    14 年前

    这里是一个C++0x替代MOO果汁的答案,在这种情况下,A的构建比 int .

    int myints[]= {10,20,30,40,50};
    size_t total(sizeof(myints) / sizeof(int));
    
    auto begin(std::make_move_iterator(myints));
    auto end(std::make_move_iterator(myints + total));
    
    std::set<int> mySet(begin, end);