我一直在研究这个问题一段时间。我有 3 个 .txt 文件,其中包含一些要在多图中读取和排列的内容,
std::multimap<std::string, std::multimap<int, int>>
但是如果键已经存在,我增加值,如果键是唯一的,我把值放在地图中。
3 个 .txt 文件(标记为“x”、“y”和“z”)包含以下内容:
“x.txt”包含主键:
a a a b b b c c c d d d e e e
“y.txt”包含辅助键:
1 2 2 3 4 4 5 4 4 2 6 6 6 6 6
和计算辅助键的“z.txt”包含:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
所需的输出是这样的:
1 : 1
2 : 2
3 : 1
4 : 2
5 : 1
4 : 2
2 : 1
6 : 2
6 : 3
其中指出 a 中有一个 1,a 中有两个 2,b 中有一个 3,b 中有两个 4……等等。
我的代码(如下)错误地产生了这个结果:
1 : 1
2 : 1
2 : 1
2 : 1
3 : 1
4 : 1
4 : 1
5 : 1
6 : 1
6 : 1
6 : 1
这是代码:有什么建议吗?
//needed to output your result (print map)
template<typename a, typename b>
void print1(const std::multimap<a, b>& thing){
for (std::multimap<a,b>::const_iterator it = begin(thing); it != thing.end(); it++){
std::cout << it->first << " : " << it->second << std::endl;
}
}
std::ifstream X("x.txt");
std::ifstream Y("y.txt");
std::ifstream Z("z.txt");
typedef std::multimap<int, int> Y_Z;
typedef std::multimap<std::string, Y_Z> X_Y_Z;
typedef std::pair<int, int> pair_y_z;
typedef std::pair<std::string, Y_Z> pair_x_y_z;
Y_Z y_z;
X_Y_Z x_y_z;
std::string x_;
int y_;
int z_;
if (X){
while (X >> x_, Y >> y_, Z >> z_){
if (x_y_z.empty()) {
y_z.insert(pair_y_z(y_, z_));
x_y_z.insert(pair_x_y_z(x_, y_z));
}
else {
X_Y_Z::iterator first_iter = x_y_z.find(x_);
X_Y_Z::iterator last_iter = x_y_z.upper_bound(x_);
if (x_y_z.find(x_) == x_y_z.end()) {
y_z.insert(pair_y_z(y_, z_));
x_y_z.insert(pair_x_y_z(x_, y_z));
}
else{
for (; first_iter != last_iter; first_iter++){
if (x_y_z.find(x_)->second.find(y_) == x_y_z.find(x_)->second.end()){
//no match
y_z.insert(pair_y_z(y_, z_));
x_y_z.insert(pair_x_y_z(x_, y_z));
break;
}
else{
//found match
x_y_z.find(x_)->second.find(y_)->second += z_;
break;
}
}
}
}
}
}
std::cin.get();
print1(y_z);
std::cin.get();