【问题标题】:How can I compare comparing contents of std::vectors with custom objects如何使用自定义对象比较比较STD :: Vectors的目录
【发布时间】:2016-05-17 13:50:50
【问题描述】:

我有 2 个向量,其中包含我在单元测试中使用的自定义对象。我无法更改向量中包含的对象的实现,并且对象不包含 == 重载。

我想在单元测试结束时比较这些向量中的每个对象,以确定它们在其中一个成员变量中是否具有相同的值。

目前我正在对向量进行排序,然后像这样循环遍历内容:

// Sort predicate
bool SortHelper(MyObject& w1, const MyObject& w2)
{
    return (w1.MyInt() < w2.MyInt());
};

... 

//Ensure the sent and received vecs are the same length
ASSERT_EQ(vectorOne.size(), vectorTwo.size());

// Sort the vectors
std::sort(std::begin(vectorOne), std::end(vectorOne), SortHelper);
std::sort(std::begin(vectorTwo), std::end(vectorTwo), SortHelper);

// Ensure that for each value in vectorOne there is a value for vector2
auto v1Start = std::begin(vectorOne);
auto v1End = std::end(vectorOne);
auto v2Start = std::begin(vectorTwo);
auto v2End = std::end(vectorTwo);

if ((v1Start != v1End) && (v2Start != v2End))
{

    while (v1Start != v1End) {
        EXPECT_TRUE(v1Start->MyInt() == v2Start->MyInt());
        ++v1Start;
        ++v2Start;
    }
}

我也尝试了一些 std::find_if 的组合来实现这个目标,但我没有找到解决方案。

我知道在 C# 中我可以像这样比较内容:

foreach (MyObject m in listOne)
{
    Assert.IsTrue(listTwo.Any(i => m.MyInt == i.MyInt));
}

谁能告诉我一个更好/更简洁的方法来比较我的向量的内容。我想尽可能使用 STL 和/或 Boost

【问题讨论】:

    标签: c++ c++11 boost vector stl


    【解决方案1】:

    您可以将std::equal 与适当的谓词一起使用:

    bool ok = equal(begin(vectorOne), end(vectorOne),
                    begin(vectorTwo), end(vectorTwo),
                    [](const MyObject& w1, const MyObject& w2)
                    { return w1.MyInt() == w2.MyInt(); });
    

    上述重载在 C++14 之前不可用,因此您需要在检查向量的长度是否相同后调用它:

    bool ok = equal(begin(vectorOne), end(vectorOne),
                    begin(vectorTwo),
                    [](const MyObject& w1, const MyObject& w2)
                    { return w1.MyInt() == w2.MyInt(); });
    

    【讨论】:

    • 如果您使用std::equal 的两个范围版本(而不是范围半),则会自动检查相同的长度。
    • 在 C++11 之前的版本中,不存在 lambda,如果您定义自定义全局 bool operator==(const MyObject&amp;, const MyObject&amp;) 或可以传递给 @ 的自定义谓词,您仍然可以使用 std::equal() 987654328@.
    • @BenjaminLindley 好点。我忘了在 C++14 中添加了两个范围的版本。
    • 我使用的是 C++ 11(Visual Studio 2010,所以主要是 C++ 11)所以我认为以上正是我想要的......首先检查长度。
    • @juanchopanza:对于 c++14,您可以使用 cbegin/cendauto&amp; 作为 lambda
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多