c++ - How to compare vector with array in efficient way in cpp? -


i write code in better (faster) way. have got container vector , simple array. compare content of vector content of array. suppose have got classes this:

struct {     float aa;     struct(float p_aa) : aa(p_aa) {} };  struct b : public {     bb;     struct(float p_aa) : a(p_aa) {} }; 

and have container , simple array:

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

the function, compare container array is:

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

i write in better way using lambda or foreach. have ideas? thanks.

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 both , code presupposes vector , array have same size. better implementation additionally pass in length of l_b can ensure don't read uninitialized memory 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 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); } 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -