loops - C++ - Alternative to iterating vector -
i have std::vector<myclass*>
(a vector of myclass pointers), , need find particular item in vector. class has getid()
function returns unique identifier of class.
if want find class specific id, iterate through vector looking class id, this:
for(std::vector<chunk*>::iterator = chunksrenderlist.begin(); != chunksrenderlist.end(); ++it) { if((*it)->getid() == id) return *it; }
this rather slow because calling code lots of times per second. have tried using std::unordered_map
lot slower, , std::map
slower again. i'm not sure why slower, maybe it's way used it.
is there container/algorithm can use access particular item without having iterate (that faster iteration)?
if container sorted accoding value of getid() may try using binary search.
class { size_t m_id; public: (size_t id) : m_id(id) {} size_t getid (void) const { return m_id; } }; template<class t1, class t2> struct less_id { bool operator () (t1 const &lhs, t2 const & cmp) { return (lhs->getid() < cmp); } }; int main (void) { std::vector<a*> v; v.push_back(new a(2)); v.push_back(new a(3)); v.push_back(new a(4)); v.push_back(new a(5)); less_id<a*, size_t> cmp; size_t find_value = 4; std::vector<a*>::iterator found = std::lower_bound(v.begin(), v.end(), find_value, cmp); if(found == v.end() || !((*found)->getid() == find_value)) { // not found } else { // found std::cout << "found element: " << (found-v.begin()) << std::endl; } (size_t i=0; i<v.size(); ++i) delete v[i]; v.clear(); }
shows
found element: 2
where a
== chunk
, v
== chunksrenderlist
.
Comments
Post a Comment