c++ - 如何正确地将 const_iterator& 传递给函数?
问题描述
假设我有一个整数向量,并希望以一种奇怪的递归方式处理它(如果没有上下文,这种情况可能听起来很奇怪,但仍然如此)。
我想使用 const_iterators 来跟踪当前位置。这是odd_recursive_stuff()
原型:
// Note: changing "std::vector<int>::const_iterator& it_cur"
// into "std::vector<int>::const_iterator it_cur" will change
// the side effects!
void odd_recursive_stuff (std::vector<int>::const_iterator& it_cur,
std::vector<int>::const_iterator it_end);
首先,我尝试这样称呼它:
void process_vec (const std::vector<int> &vec) {
odd_recursive_stuff (std::begin(vec), std::end(vec));
}
幸运的是,它没有编译(例如在 clang 8.0.0 中):
Error: no matching function for call to 'recursive_odd_stuff'
Candidate function not viable: expects an l-value for 1st argument!
因为std::begin()
返回 r 值,所以我必须以另一种方式调用它:
void process_vec (const std::vector<int> &vec) {
std::vector<int>::const_iterator it_beg = std::begin (vec);
recursive_odd_stuff (it_beg, std::end(vec));
}
现在我想知道是否可以在recursive_odd_stuff()
没有 local_variable 的情况下用单行it_beg
调用 base ?
似乎不可能编写另一个begin()
返回左值的版本,因为“当且仅当它是引用时,函数的返回值才是左值(C ++ 03)。(5.2.2 [ expr.call] / 10)"。所以唯一的方法是用两条线调用它?
解决方案
超载!
有一个只接受右值的版本:
void odd_recursive_stuff (std::vector<int>::const_iterator&& it_cur,
std::vector<int>::const_iterator it_end);
…以及一个接受左值引用的版本(并为您做额外的行):
void odd_recursive_stuff (const std::vector<int>::const_iterator& it_cur,
std::vector<int>::const_iterator it_end)
{
std::vector<int>::const_iterator it_copy(it_cur);
odd_recursive_stuff(std::move(it_copy), it_end);
}
这与移动语义所基于的原则相同,因为复制和移动构造函数的选择方式相同。
但是你可能会考虑放弃这整件事,而只返回新的值it
:
std::vector<int>::const_iterator
odd_recursive_stuff(std::vector<int>::const_iterator it_cur,
std::vector<int>::const_iterator it_end);
然后,您可以随意丢弃它。
没有人真正期望迭代器被引用。
推荐阅读
- java - 使用 Selenium 上传 APK 文件
- node.js - 如何使用具有不同查询参数的相同路由
- java - 如何使用icu4j在java中将单词转换为数字
- android - 将 Firebase 添加到我的 Android 项目时出错
- reactjs - React Google Analytics - 如何检查是否已初始化?
- python - 硒复选框单击在python中不起作用
- hangfire - 如何让 Hangfire 挑选工作在最后一小时内排队?
- php - 我如何在同一服务器和域上运行 php 和 django
- c++ - 编译器何时自动调用移动语义?
- rust - 包含用于初始化 Trie 结构的大型源文件的 Rust crate 无法编译 (OOM)