2

I would like to write a code in a better (faster) way. I have got a container vector and an simple array. I would like to compare content of the vector with content of the array. Suppose that I have got classes like this:

struct A
{
    float aa;
    struct(float p_aa) : aa(p_aa) {}
};

struct B : public A
{
    A bb;
    struct(float p_aa) : A(p_aa) {}
};

And I have also a container and an simple array:

std::vector<B> l_v = {B(1), B(3)};
B l_b[2] = {B(1), B(3)};

The function, which compare the container with the array is:

bool isTheSame(const std::vector<B> &l_v, B *l_b)
{
    unsigned int count = 0;
    for(auto it = l_v.begin(); it!= l_v.end(); ++it)
    {
        if(l_b[count].aa != it->aa)
        {
            return false;
        }
        ++count;
    }
    return true;
}

I would like to write it in a better way using lambda or foreach. Do you have any ideas? Thanks.

1

1 Answer 1

8

Use std::equal:

bool isTheSame(const std::vector<B> &l_v, B *l_b)
{
    return std::equal(l_v.begin(), l_v.end(), l_b,
                      [](const B& lhs, const B& rhs){
                          return lhs.aa == rhs.aa;
                      });
}

Note that both this and your code presupposes that the vector and the array have the same size. A better implementation would be to additionally pass in the length of l_b so that you can ensure that you don't read uninitialized memory from l_b:

bool isTheSame(const std::vector<B> &l_v, B *l_b, size_t len)
{ 
    return len == l_v.size() && 
        std::equal(l_v.begin(), l_v.end(), l_b, same_pred);
}

Or as an array:

template <size_t N>
bool isTheSame(const std::vector<B> &l_v, const B (&l_b)[N])
{ 
    return N == l_v.size() && 
        std::equal(l_v.begin(), l_v.end(), l_b, same_pred);
}
Sign up to request clarification or add additional context in comments.

1 Comment

The only reason you need to pass the length is because you decided to pass a pointer instead of a reference to an array. There's no need for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.