How to make a fast search for an object with a particular value in a vector of structs or classes? c++

前端 未结 4 2014
无人及你
无人及你 2021-01-24 06:38

If I have thousands of struct or class objects in a vector, how to find those that are needed, in a fast way?
For example:
Making a game, and I need fas

相关标签:
4条回答
  • 2021-01-24 06:57

    You should sort your vector and then use the standard library algorithms like binary_search, lower_bound, or upper_bound.

    The above will give you a better compliexity than o(n) given by walk through of entire vector or by using standard library algorithm find.

    0 讨论(0)
  • 2021-01-24 06:58

    A vector is just an unordered collection of objects. There is not really anyway to do what you are asking unless you start sorting your vector in specific ways (e.g. if it is sorted you can jump to the middle of the vector and potentially split your search time in half)

    You may be better off picking a different data structure (either instead of the vector or in combination with it)

    0 讨论(0)
  • 2021-01-24 07:18

    i think you have to go more in depth that the simple research of a value inside a group of struct, even more if you are planning on searching among a elevated number. How are the struct generated, how are they collected and how you keep track of them, there is a common key that you can you can use to order while you create them?

    You should focus on sorting them while you add it to the whole structure, that way you avoid massive computation burst every time you have to perform a search. Choose a good algorithm (example AVL sorting), that way you can have a O(log(n))) adding/delete/searching.

    0 讨论(0)
  • 2021-01-24 07:20

    For example:

    for_each(v.begin(),v.end(), [](int e) 
    {
        if (e%2==1)//vector elements that are not divided by 2 without remainder
        cout<<e<<endl;
    });
    
    0 讨论(0)
提交回复
热议问题