【发布时间】:2017-02-21 11:38:19
【问题描述】:
我正在使用std::mismatch 来检查两个结构向量是否完全相同。通常,在我的程序中,它们不是,但在特殊情况下可能会发生。在documentation 我发现以下内容:
“如果两个序列中比较的元素都匹配,则函数返回一个对,其中第一个设置为last1,第二个设置为第二个序列中相同相对位置的元素。”
但是,如果我创建两个完全相等的向量,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 Studios 15 中运行此代码时,我收到一条错误消息:
return (compare_structs(*mypair.first, *mypair.second));
经过进一步调查,结果发现 mypair 在不匹配后仍然为空。从文档中,我虽然这将返回每个向量的最后一个值。我是否误解了当出现 2 个所有元素都匹配的序列时不匹配的表现?
【问题讨论】:
-
“我遇到了一个错误”——您愿意与您的听众分享该错误的性质吗? (从“输出”窗口复制和粘贴。)
-
而here 是一个更可靠的参考网站。