简体   繁体   中英

What's the fastest way to check which values I've used so far in C++?

A snippet

if (a<=lim){
    if(std::find(prims.begin(), prims.end(), a)==prims.end()){
        prims.push_back(a);
        count+=lim/a;
    }         
}

So basically I have this part in my code where I add the variable a into this vector if it isn't already present, and then I update a counter on the fly.

But I am wondering if this is suboptimal in terms of runtime. Anything faster I can do?

std::set Is a container that is used commonly if you want to only keep unique values. Values are internally stored as red-black trees so most operations are of logarithmic complexity.

This would be faster than your implementation, and about as fast as the suggested binary search implementation.

You can improve it further by using the new (c++11) std::unordered_set , which stores it as a hash table, which would make it even faster at average constant time operations.

Use set as follows

std::set<TYPE> prims;
....
if (a<=lim){
    if(prims.insert(a).second){
        count+=lim/a;
    }         
}

where TYPE is the type of the values stored in your vector

You can use a std::unordered_set to check for duplicates, which gives you O(1) amortized lookup.

If you kind of know the maximum size of a and it's fairly small, you can use a bool array to store whether element x and you'll have true O(n) lookup.

You want to use other STL containers with uniqueness builtin, like the set , or map ; http://www.cplusplus.com/reference/map/map/ . For example, a hashtable modeled by a map, fits your use case.

<map>
using namespace std;

int insert_and_update(int key_val,map<int,int> hash_map) {
map<int,int>::iterator it;
it = hash_map.find(key_val);
  if( it != hash_map::end() ) {
     it->second += 1; //contains the associated value.
     return 1;
  }
 hash_map(key_val) = 1; //else insert new key into map
 return 0;      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM