[英]Merging two stl containers without std::merge
I have to write a merging function that merges two stl containers without using std::merge. 我必须编写一个合并功能,无需使用std :: merge即可合并两个stl容器。 I wanted to use the implementation of std::merge, though.
我想使用std :: merge的实现。
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator merge (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2,
OutputIterator result) {
while (true) {
if (first1==last1)
return std::copy(first2,last2,result);
if (first2==last2)
return std::copy(first1,last1,result);
*result++ = (*first2<*first1)? *first2++ : *first1++;
}
}
I wanted to test it with this: 我想用这个来测试它:
std::vector<int> v1;
v1.push_back(1);
v1.push_back(7);
std::list<int> l1;
l1.push_back(23);
l1.push_back(3);
std::vector<int> v2;
std::vector<int>::iterator first1 = v1.begin(), last1 = v1.end(), output = v2.end();
std::list<int>::iterator first2 = l1.begin(), last2 = l1.end();
merge<std::vector<int>::iterator, std::list<int>::iterator, std::vector<int>::iterator>(first1, last1, first2, last2, output);
Why does this produce a run time error saying "Vector iterator not incrementable" ? 为什么这会产生一个运行时错误,提示“向量迭代器不可递增”?
EDIT: Thanks for the answers, merging works but the output is unsorted 编辑:感谢您的答案,合并工作,但输出未排序
You need to allocate memory for v2 to make the output result iterator dereferencable. 您需要为v2分配内存,以使输出结果迭代器可取消引用。
std::vector<int> v2( v1.size() + l1.size() );
And output = v2.begin();
并
output = v2.begin();
You're trying to write to, and beyond, v2.end()
. 您正在尝试编写
v2.end()
以及以后的v2.end()
。 This won't grow v2
, it will just trample over invalid memory, giving undefined behaviour. 这不会增长
v2
,只会践踏无效内存,从而产生不确定的行为。
Either make v2
large enough to write into: 使
v2
足够大以写入:
std::vector<int> v2(v1.size() + l1.size());
auto output = v2.begin();
or use an insertion iterator 或使用插入迭代器
std::vector<int> v2;
auto output = std::back_inserter(v2);
By the way, there should be no need to specify the template arguments when calling merge
; 顺便说一句,在调用
merge
时,无需指定模板参数。 they can be inferred from the function arguments: 它们可以从函数参数中推断出来:
merge(first1, last1, first2, last2, output);
Your code can be rewritten the following way 您的代码可以通过以下方式重写
std::vector<int> v1;
v1.reserve( 2 );
v1.push_back(1);
v1.push_back(7);
std::list<int> l1;
l1.push_back(23);
l1.push_back(3);
std::vector<int> v2;
v2.reserve( v1.size() + l1.size() );
merge( v1.begin(), v1.end(), l1.begin(), l1.end(), std::back_inserter( v2 ) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.