首页 > 解决方案 > C++ 中的映射出现

问题描述

在下面的代码中,我总是可以打印出向量中数字的“出现次数”。如果您打印出来,您会看到,它正在打印向量元素中重复甚至根本不重复的所有数字。

打印出来的数字是:

1: 0                                                                       
2: 4                                                                       
5: 5                                                                       
6: 2 3                                                                     
7: 6 7 8 9                                                                 
8: 1 10 

我感兴趣的是我总能从打印的数组中找到向量位置 [i] 之间的差异:

cout << occurrences[6][0] - occurrences[6][1]  << endl;

在上述情况下,我确实取了元素“6”的第一个位置和元素“6”的第二个位置之间的“位置差异”。但是我怎么能在不知道打印出来的数字的情况下做到这一点呢?我的意思是我会想找到第一个和第二个重复数字之间的“位置差异”(如果有的话,例如,因为 0 没有重复两次,所以我不会考虑那个数字或者我不会找到该数字的差异也是如此)

#include<iostream>
#include<vector>
#include<map>

using namespace std;

int main() {
  vector<int> ar{ 1, 8, 6, 6, 2, 5, 7, 7, 7, 7, 8 };
  map<int, vector<size_t> > occurrences{ };

  for (size_t i = 0; i < ar.size(); ++i) {
    occurrences[ar[i]].push_back(i);
  }

  for (const auto& occurrence:occurrences) {
    cout << occurrence.first << ": ";
    for (auto index: occurrence.second) {
      cout << index << " ";
    }
    cout << endl;
  }

  return 0;
}

标签: c++

解决方案


我认为您在这里缺少的功能是 find() http://www.cplusplus.com/reference/map/map/find/

假设您只想找到第一次两次出现之间的距离,我将您的代码更新为以下内容,

#include<iostream>
#include<vector>
#include<map>

using namespace std;

int main() {
  vector<int> ar{ 1, 8, 6, 6, 2, 5, 7, 7, 7, 7, 8 };
  map<int, vector<size_t> > occurrences;

  for (size_t i = 0; i < ar.size(); ++i) {
    auto iter = occurrences.find(ar[i]);
    if (iter == occurrences.end()) {
      occurrences[ar[i]].push_back(i);
    }
    else { //print the distance between the current and the previous occurrence
      cout << "distance with first occurrence of number "  << ar[i] << " is " << (i - iter->second[0]);
    }
  }
  return 0;
}

推荐阅读