Does C++ have any type of hash? I know in ruby you could create hashes but does C++ have this? And if it does can you show me an example of how to use it? If not then is there something similar to a hash?
Does C++ have any type of hash? I know in ruby you could create hashes but does C++ have this? And if it does can you show me an example of how to use it? If not then is there something similar to a hash?
C++ has no hash table. The map class is similiar, but it's not hash based (lookups are slower, but it keeps the data ordered, note how the output is printed in alphabetical order). I can almost guarentee hash maps will be in the next version of the standard, and it's a pretty big lack IMO.
Code:#include <iostream> #include <map> #include <string> int main() { std::map<std::string, int> nameToNum; nameToNum["one"] = 1; nameToNum["two"] = 2; nameToNum["three"] = 3; nameToNum["four"] = 4; std::cout << nameToNum["three"] << std::endl; for (std::map<std::string,int>::iterator i = nameToNum.begin(); i != nameToNum.end(); ++i) { std::cout << i->first << ' ' << i->second << std::endl; } return 0; }
I may be in the minority, but I don't really see the point in hash tables. If you have ot use a hash table then you can probably recode it to be more efficient. But that is just my opinion.
Recode what? If you want to search fast, hash tables work nicely.
Munkey01, it is a matter of time.
Programming should be efficient. For example, I *could* write my own more efficient I/O classes, but it will take time which can be spent elsewhere.
Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling
Thanks guys. I just wanted to know because I know when i used Ruby they came in handy.
>>If not then is there something similar to a hash?
You can make your own hash with a vector and list pretty easily.
Code:#include <iostream> #include <string> #include <vector> #include <list> using namespace std; const int hsize = 101; int my_hash(string str) { int h = 0; string::iterator iter; for (iter = str.begin(); iter != str.end(); ++iter) { h = *iter + 31 * h; } return h % hsize; } string my_lookup(vector<list<string> >& table, string& item) { list<string> tlist = table[my_hash(item)]; list<string>::iterator iter; for (iter = tlist.begin(); iter != tlist.end(); ++iter) { if (*iter == item) { return *iter; } } return ":nonexistant:"; } int main() { string word; vector<list<string> > table(hsize); table[my_hash("now")].push_front("now"); table[my_hash("is")].push_front("is"); table[my_hash("the")].push_front("the"); table[my_hash("time")].push_front("time"); cout<<"Enter a word to find: "<<flush; getline(cin, word); cout<<"Found -- "<< my_lookup(table, word) <<endl; }
*Cela*
STLport includes the common extention hash_map, it's worthwile for the debug mode alone. As others have said this will probably make it to the next version of the standard. I still recomend writing your own, builds character.