比较两个向量. [英] Comparing two vectors.

查看:126
本文介绍了比较两个向量.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我想知道是否有一个有效的算法来比较两个向量.我要完成的目的是检查两个向量是否相同.会使用此代码来覆盖==运算符.

如果有人有任何建议,我将不胜感激,因为我现在尝试的方法远远不能比较10000个元素.

这是我现在拥有的代码:

Hi Everyone,

I am wondering if there is an efficient algorithm to compare two vectors. The purpose of what I am trying to accomplish is to check if two vectors are the same. This code is attended to override the == operator.

If anyone has any suggestions or advice I would much appreciated it because the method I am trying now is far to slow to compare 10000 elements.

Here is the code I have now:

inline bool operator == (Journal const& lhs, Journal const& rhs)
{
        if (lhs.get_record_size() != rhs.get_record_size())
                return false;
        record_size num = lhs.get_record_size();
        for(record_size i = 0; i < num; ++i)
        {
                if (lhs.get_record()[i]!= rhs.get_record()[i])
                        return false;
        }
        return true;
}




非常感谢大家的时间,
谢谢!

robNO.

更新的代码(更快):




Everyone''s time is greatly appreciated,
Thanks!

robNO.

UPDATED CODE ( THAT IS MUCH FASTER ):

inline bool operator == (Journal const& lhs, Journal const& rhs)
{
        if (lhs.get_record_size() != rhs.get_record_size())
                return false;
        if (lhs.get_record() != rhs.get_record())
                return false;
        return true;
}



感谢您提供更多建议!

谢谢大家!!!
robNO.



More advice is appreciated!

Thanks Everyone!!!
robNO.

推荐答案

为什么不只使用lhs==rhs?
 
向量具有 operator == .
 
Why not just use lhs==rhs?
 
Vectors have an operator==.
 


我会选择使用迭代器.

如果不使用迭代器,那么我至少可以使用


1)size_t const record_size = lhs.get_record_size();

在循环之前.这样,优化器可以清楚地知道该值在循环中不会更改.

2)根据类的简单程度,您也许可以在比较运算符中使用memcmp.
如果vector实际上在一个连续的物理块中分配了所有内存,则可以使用memcmp轻松检查.

请注意以下(草药销售商)
I would time using iterators instead.

If not using iterators, then I might at least use


1) size_t const record_size=lhs.get_record_size();

before the loop. That way it is clearer to the optimizer that the value does not change in the loop.

2) Depending on how simple your class is, you might be able to use memcmp in your comparison operator.
If vector actually allocated all of the memory in a contiguous physical block then you could have an easy check using memcmp.

Note the following (Herb Sutter)
It’s so important, in fact, that when it was discovered that the C++98 standard didn’t completely guarantee contiguity, the C++03 standard was amended to explicitly add the guarantee.


这篇关于比较两个向量.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆