c++ - 合并函数未正确复制到向量中
问题描述
应该接受 5 个迭代器,拆分发送的merge(iterator, iterator, iterator2, iterator2, outIterator)
向量,然后对 2 个单独的向量进行排序,然后将它们合并为一个排序的向量。我的方法似乎有效,除非range2
元素少于range1
我的测试失败。
template<typename Iter1, typename Iter2, typename OIter>
OIter merge(Iter1 first1, Iter1 last1, Iter2 first2, Iter2 last2, OIter out) {
// TODO
auto i = first1;
auto j = first2;
while (j != last2 && i != last1) {
if (first2 == last2) {
return std::copy(first1, last1, out);
}
if (*i < *j) {
*out++ = *i++;
} else {
*out++ = *j++;
}
}
//only one of the ranges has elements copy them over
if (first2 == last2) {
return std::copy(first1, last1, out);
} else {
return std::copy(first2, last2, out);
}
}
测试:
REQUIRE( out == copy_out )
扩展:
{ 0, 1, 2, 3, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0 } = actual
==
{ 0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 } = expected
解决方案
这个逻辑是错误的
//only one of the ranges has elements copy them over
if(first2 == last2)
{
return std::copy(first1, last1, out);
}else{
return std::copy(first2, last2, out);
}
它应该是
//only one of the ranges has elements left, copy them over
if(j == last2)
{
return std::copy(i, last1, out);
}else{
return std::copy(j, last2, out);
}
还有这种特殊待遇
if(first2 == last2)
{
return std::copy(first1, last1, out);
}
是不必要的(并且放错了位置)。
推荐阅读
- swiftui - SwiftUI 中 Text 对象中使用的当前字体
- postgresql - 无法在 postgresql 中创建关系表
- angular - 带有文本字段参数的自定义验证器
- python - 如何在使用 end='' 时交替打印 2 个不同的字符串?
- java - 无法使用 JSoup 解析 HTML
- android - wifi直接直播摄像头视频流
- python - 是否有必要在python的覆盖方法中使用构造函数
- django - 获取 Wagtail 页面模型的随机对象,但不是当前对象
- javascript - 删除内容时返回原始输入类
- python - 测试失败:“类型”对象不可迭代