Home > Blockchain >  How make set function faster?
How make set function faster?

Time:04-07

How make set function faster?

set<unsigned long> k;
unsigned long s = pow(2,31);
for(unsigned long i = 0; i < s; i  ){
    k.insert(i);
}
cout << k.size() << endl;

Code runs very long? So have new method in order to run faster?

CodePudding user response:

How make set function faster?

You can make this faster by using hints, since you know that every insert is to the end of the set:

for(unsigned long i = 0; i < s; i  ){
    k.insert(k.end(), i);
}

Alternatively, you could potentially make it faster using another data structure, such as std::unordered_set for example.

Most significantly, you could make it faster by not creating such a massive set in the first place. For example, if you need to know whether some unsigned long ul is in the set of integers [0, s), then you can simply use ul < s instead of creating the set that contains all the integers.

  •  Tags:  
  • c
  • Related