gpt4 book ai didi

c++ - 合并功能未正确复制到 vector 中

转载 作者:行者123 更新时间:2023-12-02 10:17:43 28 4
gpt4 key购买 nike

merge(iterator, iterator, iterator2, iterator2, outIterator)应该包含5个迭代器,拆分发送的 vector ,然后对2个单独的 vector 进行排序,然后将它们合并为一个排序的 vector 。除非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);
}

是不必要的(并且放错了位置)。

关于c++ - 合并功能未正确复制到 vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61395674/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com