New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

more C like C++ #3

Closed
tedu opened this Issue Feb 6, 2014 · 1 comment

Comments

Projects
None yet
2 participants
@tedu

tedu commented Feb 6, 2014

Here is a more C like C++ implementation. :)

It's a fair bit faster because std::string is slow. Still using hash_map because it's convenient.

include <stdio.h>

include

using namespace std;

include <ext/hash_map>

using namespace __gnu_cxx;

int
readline(FILE _fp, char *_item, char *_feat, char *_val)
{
char *p;
static char buf[1024];

    if (!fgets(buf, sizeof(buf), fp))
            return 0;
    *item = buf;
    p = strchr(buf, ' ');
    *p = 0;

    *feat = p + 1;
    p = strchr(p + 1, ' ');
    *p = 0;

    *val = p + 1;
    p = strchr(p + 1, '\n');
    *p = 0;
    return 1;

}
struct eqstr
{
bool operator()(const char* s1, const char* s2) const
{
return strcmp(s1, s2) == 0;
}
};

int main(int argc, const char argv)
{
hash_map<const char
, int, hash<const char
>, eqstr> imap;
hash_map<const char*, int, hash<const char*>, eqstr> jmap;
hash_map<const char*, int, hash<const char*>, eqstr> I;
int J=0;
FILE *vocab = fopen("vocab", "w");

typeof(imap.end()) imapend = imap.end();
typeof(jmap.end()) jmapend = jmap.end();

for (int file_i=1; file_i<argc; file_i++) {
printf("%s\n",argv[file_i]);

const char *filename = argv[file_i];
FILE *in = fopen(filename, "r");
char outname[1024];
snprintf(outname, sizeof(outname), "%sn", filename);
FILE *out = fopen(outname, "w");

I[strdup(filename)] = 0;

char *item, *feat, *val;

while (readline(in, &item, &feat, &val)) {
  char key[1024];
  snprintf(key, sizeof(key), "%s %s", filename, item);
  if (imap.find(key) == imapend) {
    imap[strdup(key)] = ++I[filename];
  }
  if (jmap.find(feat) == jmapend) {
    jmap[strdup(feat)] = ++J;
    fprintf(vocab, "%s\n", feat);
  }
  fprintf(out, "%d %d %s\n", imap[key], jmap[feat], val);
}

}
return 0;
}

@brendano

This comment has been minimized.

Show comment
Hide comment
@brendano

brendano Feb 7, 2014

Owner

cool! if you can submit this as a pull request i'll merge. (it would be nice to confirm it gets the same answer as the other implementations...)

Owner

brendano commented Feb 7, 2014

cool! if you can submit this as a pull request i'll merge. (it would be nice to confirm it gets the same answer as the other implementations...)

@brendano brendano closed this Feb 7, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment