What#39;s wrong with passing C++ iterator by reference?(通过引用传递 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++ 迭代器有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过引用传递 C++ 迭代器有什么问题?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01