迭代器不兼容错误
我想写一个函数,它需要两个向量并将它们合并在一起,来回交替(即v1 = 1,2,3 v2 = 4,5,6会产生v3 = 1,4 ,2,5,3,6)。问题是,当我运行我的函数时,我得到一个错误,说'矢量迭代器是不兼容的'。从我的研究中,我认为它与我使用.begin()和.end()函数有关,但是由于我仅仅在这几个月内就看到了,所以我不知道如何修复它。注意:NULL上的push_back是在向量中留下一个空白空间。迭代器不兼容错误
下面的代码:
void merge(vector<double> x, vector<double> y, vector<double>& merged) {
auto xStart = x.begin();
auto yStart = y.begin();
while (xStart != x.end() && yStart != x.end()) {
merged.push_back(*xStart);
merged.push_back(*yStart);
++xStart;
++yStart;
}
if (xStart != x.end()) {
while (xStart!= x.end()) {
merged.push_back(*xStart);
merged.push_back(NULL);
++xStart;
}
}
if (yStart != y.end()) {
while (yStart != y.end()) {
merged.push_back(*yStart);
merged.push_back(NULL);
++yStart;
}
}
}
有一个错字
while (xStart != x.end() && yStart != x.end()) {
^^^^^^
必须有
while (xStart != x.end() && yStart != y.end()) {
^^^^^^^
而且这种说法
merged.push_back(NULL);
没有意义。
而且它好得多声明函数像
void merge(const vector<double> &x, const vector<double> &y, vector<double>& merged);
这里是一个示范项目
#include <iostream>
#include <vector>
template <typename T>
void merge(const std::vector<T> &x,
const std::vector<T> &y,
std::vector<T> &merged)
{
merged.reserve(merged.size() + x.size() + y.size());
auto xStart = x.begin();
auto yStart = y.begin();
for (; xStart != x.end() && yStart != y.end(); ++xStart, ++yStart)
{
merged.push_back(*xStart);
merged.push_back(*yStart);
}
for (; xStart != x.end(); ++xStart)
{
merged.push_back(*xStart);
}
for (; yStart != y.end(); ++yStart)
{
merged.push_back(*yStart);
}
}
int main()
{
std::vector<int> v1 = { 0, 2, 4, 6, 8 };
std::vector<int> v2 = { 1, 3, 5, 7, 9 };
std::vector<int> merged;
merge(v1, v2, merged);
for (int x : merged) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
它的输出是
0 1 2 3 4 5 6 7 8 9
谢谢你的帮助!出于好奇,为什么将它们作为常量更好地发送给函数呢? – Sandweiche
@Sandweiche它们通过常量引用传递。这允许1)避免创建向量的副本,并且2)保证源向量在函数中不被改变。 –
我猜测原始代码试图填充较短的向量,例如'{1,2,3} + {4} = {1,4,2,0,3,0}' –
'yStart!= x.end( )''''''''''yStart!= y.end()' –
如果您在调试器下运行您的代码,您会发现调试器指示了线路连接保留错误 –
'push_back(NULL)'是一个错误(可能无法在较新的编译器上编译),请改用'push_back(0.0)'。 “如果(X)while(X)'是多余的,你可以直接进入'while'。 –