代码之家  ›  专栏  ›  技术社区  ›  mskfisher KeithS

从结构数组中提取结构成员

  •  0
  • mskfisher KeithS  · 技术社区  · 15 年前

    struct test_case {
        const int input1;
        //...
        const int output;
    };
    
    test_case tc[] = {
        {0,  /**/  1},
        //  ...
        {99, /**/ 17}
    };
    
    int tc_size = sizeof(tc) / sizeof(*tc);
    

    我想提取 output 所以我可以通过 BOOST_CHECK_EQUAL_COLLECTIONS .

    我想到了这个:

    struct extract_output {
        int operator()(test_t &t) {  
            return t.output;  
        }
    }
    
    std::vector<int> output_vector;
    
    std::transform(test_cases, 
                   test_cases + tc_size, 
                   back_inserter(output_vector), 
                   extract_output());
    

    但似乎我应该能够做到这一点,每种类型都没有函子/结构。

    std::transform(test_cases, 
                   test_cases + tc_size, 
                   back_inserter(output_vector), 
                   _1.output);
    

    显然 operator.() cannot be used on lambda variables ... 我该用什么?boost::绑定?

    1 回复  |  直到 15 年前
        1
  •  2
  •   mskfisher KeithS    15 年前

    是的,添加boost::bind就是答案:

    std::transform(test_cases, 
                   test_cases + tc_size, 
                   back_inserter(output_vector), 
                   boost::bind(&test_case::output, _1));
    

    这有效是因为 std::transform 通过 test_case 生成函子的参数 bind() member pointer syntax (&T::x) 提取并返回成员变量。