SPOILER/CHEAT: C++ faster solution
Bryan Sant
bryan.sant at gmail.com
Fri Mar 10 17:05:37 MST 2006
On 3/10/06, Nicholas Leippe <nick at byu.edu> wrote:
> // this is nearly the same as before, but some additional thought and
> // reorganization yields substantially increased performance
>
> #include <fstream>
> #include <iostream>
> #include <map>
> #include <set>
>
> using namespace std;
>
> string<char> dictionary("/usr/share/dict/words");
>
> int main(int argc, char** argv) {
> map<string, int> words;
> map<string, int> count;
> ifstream w(argv[1]);
> ifstream d(dictionary.c_str());
> string word;
>
> while (w >> word) {
> words[word]++;
> }
>
> map<string, int>::iterator i;
> while (d >> word) {
> i = words.find(word);
> if (i != words.end()) {
> count[word] = (*i).second;
> }
> }
>
> for (i = count.begin(); i != count.end(); i++)
> {
> cout << (*i).first << ' ' << (*i).second << endl;
> }
> return 0;
> };
>
That is sweet. You're now beating my Java code by a few milliseconds
:-). I have to remove the <char> templatization on string before I
can compile though. Why is that?
gcc vesion 4.0.2 (Ubuntu...)
The output of "g++ uniq.cpp -o u" is:
uniq.cpp:8: error: 'std::string' is not a template
Once I remove the <char> portion of the declaration, all is well.
-Bryan
More information about the PLUG
mailing list