gpt4 book ai didi

C++使用第三个序列作为标准检查两个序列是否相等

转载 作者:搜寻专家 更新时间:2023-10-31 00:56:39 24 4
gpt4 key购买 nike

我需要检查两个给定序列是否相等,但如果我发现不匹配的元素,我需要检查第三个序列(与其他两个序列大小相同)是否可以忽略。

我知道我可以写一个简单的算法来解决这个问题,但我想知道是否有任何类似 C++ 的风格来解决这个问题,使用标准算法。

例子:

A = [1, 2, 3, 4, 5, 6]
B = [1, 2, 3, A, 5, 6]
M = [true, true, true, false, true, true]
N = [true, true, true, true, true, true]

bool equal1 = the_equal(begin_A, end_A, begin_B, begin_M); // Should return true, even if '4' is different from 'A' since in the same position of the found mismatch, in the M sequence, we have a false that indicates that position should be ignored.

bool equal2 = the_equal(begin_A, end_A, begin_B, begin_N); // Should return false, since '4' is different from 'A' and we have a true in sequence N for that position.

这可以通过类似的方式解决:

template<I1, I2, I3> // iterators
bool the_equal(I1 first1, I1 last1, I2 first2, I3 first3) {
while (first1 != last1) {
if (*first1 != *first2 && *first3 != false)
return false;
++first1; ++first2; ++first3;
}

return true;
}

编辑:由于工具链的限制,我忘了说我需要在 c++98 中解决这个问题 :(

最佳答案

你可以创建一个(可变的)仿函数:

template <typename IT>
struct CmpWithMask
{
CmpWithMask(IT it) : it(it) {}

template <typename LHS, typename RHS>
bool operator () (const LHS& lhs, const RHS& rhs) {
return !*it++ || lhs == rhs;
}
IT it;
};

template <typename IT>
CmpWithMask<IT> MakeCmpWithMask(IT it) { return CmpWithMask<IT>{it}; }

然后,使用 std::equal:

std::cout << std::equal(A.begin(), A.end(),
B.begin(),
MakeCmpWithMask(M.begin())) << std::endl;
std::cout << std::equal(A.begin(), A.end(),
B.begin(),
MakeCmpWithMask(N.begin())) << std::endl;

关于C++使用第三个序列作为标准检查两个序列是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39150889/

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