在c++中使用map

using Maps in C++

本文关键字:map c++      更新时间:2023-10-16

如果我有一组地址(可重复的),其中l1或l2中有命中或缺失。如何在L1和L2中找到该地址的命中/未命中次数?

map<int, pair<int, int> myMap;
while(!EOF){
    bool hit = test_bar(address); # L1
    if(!hit)
     bool hit1= test_bar(address); #L2
    myMap.insert(address,make_pair(hit, hit1));
}

这样对吗?

如果我理解得很好,建议的解决方案将不起作用,因为没有办法计算命中或未命中的数量。也许您应该考虑以下内容:counters结构体跟踪未命中和命中的l1/l2数量。c映射将每个地址映射到它的计数器。

struct counters {
    int l1_hits, l1_misses, l2_hits, l2_misses;
};
map<int, counters> c;
while (!EOF) {
    auto it = c.find(adress);
    if (it == c.end()) it = c.insert(address, {0,0,0,0});
    bool hit1 = test_bar(address); # L1
    if (hit1) ++it->second.l1_hits;
    else {
         ++it->second.l1_misses;
         bool hit2 = test_bar(address); # L2
         if (hit2) ++it->second.l2_hits;
         else ++it->second.l2_misses;
    }
}
// print
for (auto it : c) {
    cout << it.first 
        << " " << it.second.l1_hits 
        << " " << it.second.l1_misses
        << " " << it.second.l2_hits
        << " " << it.second.l2_misses << endl;
}