简体   繁体   English

我如何比较将std :: vectors的内容与自定义对象进行比较

[英]How can I compare comparing contents of std::vectors with custom objects

I have 2 vectors which contain custom objects which I am using in a unit test. 我有2个向量,其中包含在单元测试中使用的自定义对象。 I cannot change the implemetation of the objects contained in the vectors, and the objects do not contain an == overload. 我无法更改向量中包含的对象的实现,并且这些对象不包含==重载。

I would like to compare every object in these vectors to determine if they have the same value in one of the member variables at the end of my unit test. 我想比较这些向量中的每个对象,以确定在单元测试结束时它们在成员变量之一中是否具有相同的值。

Currently I am sorting the vectors and then looping over the contents like this: 目前,我正在对向量进行排序,然后像这样遍历内容:

// 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;
    }
}

I have also attempted some combinations of std::find_if to achieve this goal but I failed to find a solution. 我还尝试了std :: find_if的一些组合来实现此目标,但是我没有找到解决方案。

I know that in C# that I could compare the contents like this: 我知道在C#中,我可以像这样比较内容:

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

Can someone show me a better/more concise way for me to compare the contents of my vectors. 有人可以告诉我一种更好/更简洁的方式来比较矢量的内容。 I would like to use STL and/or Boost wherever possible 我想尽可能使用STL和/或Boost

You can use std::equal with an appropriate predicate: 您可以将std::equal与适当的谓词一起使用:

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

The above overload isn't available before C++14, so you'd need to call this one, after checking that the length of the vectors is the same: 上面的重载在C ++ 14之前是不可用的,因此在检查向量的长度相同后,需要调用此重载:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM