【发布时间】:2017-08-22 01:14:22
【问题描述】:
我正在使用 std::map() 处理 2D 表,以计算一个数字转换为另一个数字的次数。我遇到了两个问题。首先,我的第一个转换没有显示 (1->2)。其次,我所有的转换都只显示一次(2->3 和 3->1 都发生了两次)。
我明白为什么转换只发生一次。迭代器看不到 currentVal 并转到 else,在其中添加值然后退出。我不知道如何解决这个问题。任何帮助表示赞赏!
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
//import midi notes
vector <int> midiFile = {1, 2, 3, 1, 20, 5, 2, 3, 1};
//create a 2d hashmap for matrix
map <string, map <string, int> > mCounts;
//strings for the previous value and current value
string prevVal = "";
string currentVal = "";
void addNumbers(vector <int> midiFile) {
for (int i = 0; i < midiFile.size(); i++) {
currentVal = to_string(midiFile[i]);
if(prevVal == "") {
prevVal = currentVal; //first value
} else {
//playCounts is temporary map to store counts of current val in relation to previous val
map <string, int> playCounts;
map <string, int> ::iterator iterator;
iterator = playCounts.find(currentVal);
//if mCounts doesn't contain the value yet, create a new hashmap
if(iterator != playCounts.end()){
int counter = iterator -> second;
mCounts[prevVal] [currentVal] = counter + 1;
} else {
playCounts.insert(pair <string, int>(currentVal, 1));
mCounts [prevVal] = playCounts;
}
prevVal = currentVal;
}
//find values already in map
map <string, map <string, int> > ::iterator it;
it = mCounts.find(prevVal);
if (it != mCounts.end()) {
//if value is found, do nothing
} else {
mCounts.insert(pair <string, map <string, int>>(prevVal, map <string, int>()));
}
}
}
【问题讨论】:
-
尽量避免养成
using namespace std的习惯。以后可能会导致很多混乱。 -
我认为您在循环中创建
playCounts是否正确,即在每次循环迭代时创建一个空地图? -
顺便说一句:我建议使用单个地图(不是“2D”地图)并使用
2 .. 3之类的转换作为2->3之类的单个键并相应地管理计数。 -
谢谢塔德曼。是的,斯蒂芬,这是一个很好的观点。我创建它时认为每次迭代都会有不同的值,但也许我需要将
playCounts设为全局变量。 -
好的,我已将
playCounts设为全局,这已修复了大部分过渡,尽管其中一些不正确。