【问题标题】:Using STL/Boost to initialize a hard-coded set<vector<int> >使用 STL/Boost 初始化硬编码集<vector<int> >
【发布时间】:2010-04-30 05:50:46
【问题描述】:

就像这个question 已经问过的那样,我想使用 STL 初始化一个容器,其中元素以最干净的方式硬编码。在这种情况下,元素是一个双重嵌套的容器:

set<vector<int> > A;

我想(例如)将以下值放入:

A = [[0,0,1],[0,1,0],[1,0,0],[0,0,0]];

C++0x 很好,使用 g++ 4.4.1。 STL 更可取,因为我不将 Boost 用于代码的任何其他部分(尽管我不介意使用它的示例!)。

【问题讨论】:

    标签: c++ stl boost initialization


    【解决方案1】:

    这确实使用 g++ 4.4.1,带有 -std=c++0x

    #include <set>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        set<vector<int>> A = {{0,0,1},{0,1,0},{1,0,0},{0,0,0}};
    
    }
    

    【讨论】:

    • 哇,这太棒了,而且非常简单!这也应该是我链接到的问题的 答案。为什么标准需要这么长时间才能实现此功能,有什么好的理由吗?
    • @Hooked:标准并不是很快。 :)(ISO 标准之间相隔 10 年。)以前的标准还有其他需要担心的事情。
    • +1 :哇,与 g++ (GCC) 4.6.0 20100421(实验性)和 -std=c++0x 一起使用。
    • 不错。 c++0x不应该允许我们写set&lt;vector&lt;int&gt;&gt;而不是set&lt;vector&lt;int&gt; &gt;吗?
    【解决方案2】:
    #include <boost/assign/list_of.hpp> 
    #include <vector>
    #include <set>
    
    using namespace std;
    using namespace boost::assign;
    
    int main()
    {
        set<vector<int> > A;
    
        A = list_of
            (list_of(0)(0)(1))
            (list_of(0)(1)(0))
            (list_of(1)(0)(0));
            (list_of(0)(0)(0));
        return 0;
    }
    

    【讨论】:

    • 啊,我明白了,list_of 的嵌套使用,非常感谢!是否有可能仅使用单行 += 运算符来完成?
    • list_of() 对于快速代码很有用,但对于生产来说太慢且资源密集。我在单元测试中广泛使用它,但不会碰它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多