Comparison tricks in C++

前端 未结 10 1869
礼貌的吻别
礼貌的吻别 2021-01-31 16:13

A class:

class foo{
public:
    int data;
};

Now I want to add a method to this class, to do some comparison, to see if its data is equal to on

10条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-31 16:35

    There are many ways of doing this with the STL.

    If you have an incredibly large number of items and you want to test if your given item is a member of this set, use set or unordered_set. They allow you to check membership in log n and constant time respectively.

    If you keep the elements in a sorted array, then binary_search will also test membership in log n time.

    For small arrays, a linear search might however preform significantly faster (as there is no branching). A linear search might even do 3-8 comparisons in the time it takes the binary search to 'jump around'. This blog post suggests there to be a break-even point at proximately 64 items, below which a linear search might be faster, though this obviously depends on the STL implementation, compiler optimizations and your architecture's branch prediction.

提交回复
热议问题