So, I'm noob in C++ and I'm trying to use sparse_hash_map but I can't figure out why insertion into the map does not work when reading the lines from the file, but it works when I hardcode strings.
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <sparsehash/sparse_hash_map>
using google::sparse_hash_map;
using std::cout;
using std::endl;
using std::tr1::hash;
struct eqstr {
bool operator()(const char* s1, const char* s2) const {
return (s1 == s2) || (s1 && s2 && strcmp(s1, s2) == 0);
}
};
int main() {
sparse_hash_map<const char*, int, hash<const char*>, eqstr> map;
std::string str1 = "test data 1";
const char * c1 = str1.c_str();
std::string str2 = "test data 2";
const char * c2 = str2.c_str();
std::string str3 = "test data 3";
const char * c3 = str3.c_str();
map[c1] = 1;
map[c2] = 1;
map[c3] = 1;
cout << "Total: " << map.size() << endl; // 3
std::string tmpStr;
std::ifstream file;
file.open("/usr/src/test.data");
while (getline(file, tmpStr)) {
const char * c = tmpStr.c_str();
cout << c << endl; // prints row
map[c] = 1;
}
cout << "Total: " << map.size() << endl; // prints 4, but obviously it should print 9.
}
It always inserts only the first row from the file, but works when using hardcoded strings.
/usr/src/test.data
row 1
row 2
row 3
row 4
row 5
row 6
My code was compiled with g++ (Debian 4.9.2-10) 4.9.2
__cplusplus 199711L
I installed the library using the notes inside readme file (./configure, make, make install)