Which one is faster? Fragment A or Fragment B? Or would they be more or less the same?
I know they are impractical programs; this is only for learning purposes.
list<string> A(1000);
//assign random string values to each entry in A (code not shown).
//At least one of the strings is "test"
list<string>::iterator it;
//BEGINNING OF FRAGMENT A:
for(it=A.begin(); it!=A.end(); it++){
if((*it)=="test"){
cout << "found";
break;
}
}
//END OF FRAGMENT A
.
map<string,bool> B(1000);
//assign random string values to each entry in B (code not shown).
//At least one of the strings is "test".
//B[any string]=1 (code not shown)
//
//BEGINNING OF FRAGMENT B:
if(B["test"]) cout << "found";
////END OF FRAGMENT B
First of all you should profile.
Second;
they’re not equal as
B["test"]will insert an element if it isnt in the container.if(B.count("test") != 0)is the correct way to do it.Third; B is faster, and will gain the larger the container is as it will perform a binary search in a sorted container; O(log(N)) instead of O(N).
Forth; std::hash_set or hash_map is probably what youre looking for as it is even more fast then std::map