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

允我心安 提交于 2019-12-04 05:27:23

问题


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 fastest way of collision detection. Each tile is a struct, there are many tiles in the vector map, with a values: x and y. So basically I do:

For(i=0;i<end of vector list;i++)
{
 //searching if x= 100 and y =200
}

So maybe there is a different way , like smart pointers or something to search for particular objects faster?


回答1:


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.




回答2:


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.




回答3:


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)




回答4:


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;
});


来源:https://stackoverflow.com/questions/9718341/how-to-make-a-fast-search-for-an-object-with-a-particular-value-in-a-vector-of-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!