N
nw
Hi,
I'm trying to use my own class as a map key. However something strange
seems to be happening to the map which causes my program to segfault.
I'm at a loss as to what this might be. Can anyone help?
The complete example below segfaults for me under g++ 4.1.2. Using a
debugger it seems that one of the MultiDimKey objects the map is
holding becomes corrupt.
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
class MultiDimKey {
public:
MultiDimKey() : keys() {
}
MultiDimKey(const vector<string> keys_in) : keys(keys_in) {
}
bool operator<(const MultiDimKey &other) const {
const vector<string> other_keys = other.keys;
for(size_t n=0;n<keys.size();n++) {
if(keys[n] < other_keys[n]) return true;
}
return false;
}
vector<string> keys;
};
int main() {
map<MultiDimKey,int> test;
vector<string> s1;
s1.push_back("3");
s1.push_back("6");
MultiDimKey k1(s1);
test[k1]++;
vector<string> s2;
s2.push_back("5");
s2.push_back("3");
MultiDimKey k2(s2);
test[k2]++;
vector<string> s3;
s3.push_back("6");
s3.push_back("2");
MultiDimKey k3(s3);
test[k3]++;
vector<string> s4;
s4.push_back("1");
s4.push_back("2");
MultiDimKey k4(s4);
test[k4]++;
}
I'm trying to use my own class as a map key. However something strange
seems to be happening to the map which causes my program to segfault.
I'm at a loss as to what this might be. Can anyone help?
The complete example below segfaults for me under g++ 4.1.2. Using a
debugger it seems that one of the MultiDimKey objects the map is
holding becomes corrupt.
#include <vector>
#include <map>
#include <string>
#include <iostream>
using namespace std;
class MultiDimKey {
public:
MultiDimKey() : keys() {
}
MultiDimKey(const vector<string> keys_in) : keys(keys_in) {
}
bool operator<(const MultiDimKey &other) const {
const vector<string> other_keys = other.keys;
for(size_t n=0;n<keys.size();n++) {
if(keys[n] < other_keys[n]) return true;
}
return false;
}
vector<string> keys;
};
int main() {
map<MultiDimKey,int> test;
vector<string> s1;
s1.push_back("3");
s1.push_back("6");
MultiDimKey k1(s1);
test[k1]++;
vector<string> s2;
s2.push_back("5");
s2.push_back("3");
MultiDimKey k2(s2);
test[k2]++;
vector<string> s3;
s3.push_back("6");
s3.push_back("2");
MultiDimKey k3(s3);
test[k3]++;
vector<string> s4;
s4.push_back("1");
s4.push_back("2");
MultiDimKey k4(s4);
test[k4]++;
}