[英]How to compare vector with array in efficient way in cpp?
我想以更好(更快)的方式編寫代碼。 我有一個容器向量和一個簡單的數組。 我想比較矢量的內容和數組的內容。 假設我有這樣的類:
struct A
{
float aa;
struct(float p_aa) : aa(p_aa) {}
};
struct B : public A
{
A bb;
struct(float p_aa) : A(p_aa) {}
};
我還有一個容器和一個簡單的數組:
std::vector<B> l_v = {B(1), B(3)};
B l_b[2] = {B(1), B(3)};
將容器與數組進行比較的函數是:
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;
}
我想用lambda或foreach更好地編寫它。 你有什么想法? 謝謝。
使用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;
});
}
請注意,這個和您的代碼都預先假定向量和數組具有相同的大小。 更好的實現是額外傳遞l_b
的長度,以便您可以確保不從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);
}
或者作為一個數組:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.