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

查看:166
本文介绍了通过引用传递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);

这个想法是调用者将提供一定范围的字符,函数会将字符解释为一个整数值并返回它,留下一个过去的最后使用的字符开始。例如:

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天全站免登陆