Cannot use .begin() or .end() on an array

后端 未结 6 1287
陌清茗
陌清茗 2020-12-05 10:01

The error reads:

request for member \'begin\', \'end\' in \'arr\' which is non class type int[5], unable to deduce from expression error.

6条回答
  •  情歌与酒
    2020-12-05 10:18

    Perhaps here is a cleaner way to do it using templates and lambdas in c++14:

    Define:

    template
    void my_assign_to_each(Iterator start, Iterator stop, Funct f) {
        while (start != stop) {
            *start = f();
            ++start;
        }
    }
    
    template
    void my_read_from_each(Iterator start, Iterator stop, Funct f) {
        while (start != stop) {
            f(*start);
            ++start;
        }
    }
    

    And then in main:

    int x[10];
    srand(time(0));
    my_assign_to_each(x, x+10, [] () -> int { int rn{}; rn = rand(); return rn; });
    my_read_from_each(x, x+10, [] (int value) { std::cout << value << std::endl; });
    
    int common_value{18};
    my_assign_to_each(x, x+10, [&common_value] () -> int { return common_value; });
    my_read_from_each(x, x+10, [] (int value) { std::cout << value << std::endl; });
    

提交回复
热议问题