使用先前已移动的输出迭代器调用move()是标准的c++吗?
Is it standard C++ to call move() with an output iterator that has been moved previously?
在复习算法设计和学习c++ 11的同时,我想出了下面的堆排序实现:
template <typename It, typename Comp> void heapSort(It begin, It end, Comp compFunc, std::random_access_iterator_tag) { std::make_heap(begin, end, compFunc); std::sort_heap(begin, end, compFunc); } template <typename It, typename Comp, typename IterCat> void heapSort(It begin, It end, Comp compFunc, IterCat) { typedef typename It::value_type value_type; std::vector<value_type> randomAccessContainer; randomAccessContainer.reserve(std::distance(begin, end)); std::move(begin, end, std::back_inserter(randomAccessContainer)); heapSort(std::begin(randomAccessContainer), std::end(randomAccessContainer), compFunc, std::random_access_iterator_tag()); std::move(std::begin(randomAccessContainer), std::end(randomAccessContainer), begin); }
是标准的c++先从[begin, end)
移动到一个新的容器,然后再从那个容器移动到[begin, end)
吗?
是标准c++首先从[begin, end]移动到一个新的容器,然后从该容器移动到[begin, end]吗?
我最初对你使用"标准"这个词感到困惑,并编辑了问题,以便询问这是否"合法"。这个问题的答案是:"是, 这是完全合法的"。在原始范围中的元素被移动之后,它们仍然处于有效(即使未指定)状态。
因此,对std::move()
的第二次调用将只对元素进行移动赋值操作,并且这些元素的类型必须具有不带先决条件的移动赋值操作符。只要是这样,我看没有问题。
在编辑完你的问题后,我开始怀疑你是否真的想问这是否是"标准的",意思是"通常的做法",这就是为什么我恢复了原来的措辞。
这个问题的答案是"部分"。您通常会使用一对移动迭代器来初始化临时向量,而不是调用std::move
:
std::vector<value_type> randomAccessContainer(
std::make_move_iterator(begin),
std::make_move_iterator(end)
);
除此之外,你的实现在我看来是正确的。
不,不是。
我可以理解为什么你需要它是一个随机访问容器,如果它已经不是。在这种情况下,首选std::make_move_iterator
:
std::vector<value_type> randomAccessContainer(
std::make_move_iterator(begin),
std::make_move_iterator(end));
在所有其他情况下,您都希望就地排序。(除非你需要"no effects"对异常,也许)
相关文章:
- 使用CMake检测支持的C++标准
- 如何理解C++标准N3337中的expr.const.cast子句8
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 编译标准库类型
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 铸造标准::有没有回到原来的类型
- 标准 N3337 5.2.10 第 7 条中的C++"类型"是什么意思?
- this_thread::sleep_for和计时时钟之间的关系是否由C++11标准指定
- 标准库类型的赋值运算符的引用限定符
- 标准是否严格定义了该程序应该如何编译?
- 如何从Windows应用程序输出到标准?
- 安全到标准:移动会员?
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 这是否符合C++标准:双响双响,例如!!(-0.0).
- 标准::变体的赋值运算符
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 如何在 Mac 上使用 c++17 并行标准库算法?
- 强枚举类型定义:Clang Bug 还是 C++11 标准不确定性?
- 并行标准::复制复杂性