gpt4 book ai didi

c++ - 相等 vector 的返回值 std::mismatch

转载 作者:行者123 更新时间:2023-11-30 02:26:51 25 4
gpt4 key购买 nike

我正在使用 std::mismatch检查两个结构 vector 是否完全相同。通常,在我的程序中,它们不是,但在特殊情况下可能会发生。在documentation我发现以下内容:

"If the elements compared in both sequences have all matched, the function returns a pair with first set to last1 and second set to the element in that same relative position in the second sequence."

但是,如果我创建两个完全相等的 vector ,std::mismatch 不会返回值。我正在尝试做的一个小例子:

#include <vector>
#include <algorithm>
#include <utility>

struct structwithnumber {
int id;
};

bool compare_structs (structwithnumber* struct1, structwithnumber* struct2) {
return struct1->id == struct2->id;
};

bool compare_structvectors(std::vector<structwithnumber*> v1, std::vector<structwithnumber*> v2) {
if (v1.size() != v2.size())
{
return false;
}
std::pair<std::vector<structwithnumber*>::iterator, std::vector<structwithnumber*>::iterator> mypair;
mypair = std::mismatch(v1.begin(), v1.end(), v2.begin(), compare_structs);
return (compare_structs(*mypair.first, *mypair.second));
}

void simple_example() {
structwithnumber* struct1 = new structwithnumber();
structwithnumber* struct2 = new structwithnumber();
struct1->id = 1;
struct2->id = 2;
std::vector<structwithnumber*> v1;
std::vector<structwithnumber*> v2;
v1.push_back(struct1);
v1.push_back(struct2);
v2.push_back(struct1);
v2.push_back(struct2);
compare_structvectors(v1, v2);
}

当我在 visual studio 15 中运行此代码时,我在该行收到错误:

 return (compare_structs(*mypair.first, *mypair.second));

经过进一步调查,发现 mypair 在不匹配后仍然是空的。从文档中,我虽然这会返回每个 vector 的最后一个值。当出现 2 个所有元素都匹配的序列时,我是否误解了不匹配的表现?

最佳答案

std::mismatch,如果一切都匹配,则返回一个(至少一个)尾后迭代器。您不能像在 compare_structs(*mypair.first, *mypair.second) 中那样取消引用它。

代码应按如下方式测试案例:

mypair = std::mismatch(v1.begin(), v1.end(), v2.begin(), compare_structs);

if(mypair.first == v1.end()) {
// No mismatch, do something sensible
} else {
return (compare_structs(*mypair.first, *mypair.second));
}

关于c++ - 相等 vector 的返回值 std::mismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366262/

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