通过引用传递 C++ 迭代器有什么问题? [英] What's wrong with passing C++ iterator by reference?

查看:48
本文介绍了通过引用传递 C++ 迭代器有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这样的原型编写了一些函数:

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

template <typename input_iterator>
int parse_integer(input_iterator &begin, input_iterator end);

这个想法是调用者将提供一系列字符,该函数会将字符解释为整数值并返回它,将 begin 留在最后使用的字符之后.例如:

The idea is that the caller would provide a range of characters, and the function would interpret the characters as an integer value and return it, leaving begin at one past the last-used character. For example:

std::string sample_text("123 foo bar");
std::string::const_iterator p(sample_text.begin());
std::string::const_iterator end(sample_text.end());
int i = parse_integer(p, end);

这将使 i 设置为 123 并且 p 指向" foo 之前的空间.

This would leave i set to 123 and p "pointing" at the space before foo.

我被告知(没有解释)通过引用传递迭代器是一种不好的形式.是不是形式不好?如果有,为什么?

I've since been told (without explanation) that it's bad form to pass an iterator by reference. Is it bad form? If so, why?

推荐答案

确实没有错,但是肯定会限制模板的使用.你不能只放一个由其他东西返回的迭代器,或者像 v.begin() 这样生成的迭代器,因为它们是临时的.您将始终首先必须制作本地副本,这是某种不太好的样板.

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.

一种方法是重载它:

int parse_integer(input_iterator begin, input_iterator end, 
                  input_iterator &newbegin);

template<typename input_iterator>
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<typename input_iterator, typename output_iterator>
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<int> numbers;
b = parse_integer(b, end, std::back_inserter(numbers));

这篇关于通过引用传递 C++ 迭代器有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆