What's wrong with passing C++ iterator by reference?

前端 未结 7 574
隐瞒了意图╮
隐瞒了意图╮ 2020-12-24 05:13

I\'ve written a few functions with a prototype like this:

template 
int parse_integer(input_iterator &begin, input_iterato         


        
7条回答
  •  天涯浪人
    2020-12-24 06:03

    There is nothing really wrong, but it will certainly limit the use of the template. You won't be able to just put an iterator returned by something else or generated like v.begin(), since those will be temporaries. You will always first have to make a local copy, which is some kind of boilerplate not really nice to have.

    One way is to overload it:

    int parse_integer(input_iterator begin, input_iterator end, 
                      input_iterator &newbegin);
    
    template
    int parse_integer(input_iterator begin, input_iterator end) {
        return parse_integer(begin, end, begin);
    } 
    

    Another option is to have an output iterator where the number will be written into:

    template
    input_iterator parse_integer(input_iterator begin, input_iterator end,
                                 output_iterator out);
    

    You will have the return value to return the new input iterator. And you could then use a inserter iterator to put the parsed numbers into a vector or a pointer to put them directly into an integer or an array thereof if you already know the amount of numbers.

    int i;
    b = parse_integer(b, end, &i);
    
    std::vector numbers;
    b = parse_integer(b, end, std::back_inserter(numbers));
    

提交回复
热议问题