zero_field
zero_field

Reputation: 345

Map occurrence in C++

In the below code I can always print out the "number of occurrences" of a number in the vector. If you print out you will see that, it's printing all the numbers in the vector elements that are repeated or even did not repeat at all too.

The print out number would be:

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

What I'm interested in is that I can always find the difference between the vector position [i] from the printed array:

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

In the above case, I did take the "location difference" between the first position of element "6" and the second position of element "6". But how can I do this without knowing the numbers that printed out? I mean I will want to find the "position difference" between the first and second repetitive numbers (if there is any, for example, because 0 did not repeat twice, so I won't consider that number or I won't find the difference of that number as well)

#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;
}

Upvotes: 0

Views: 1001

Answers (1)

sud_
sud_

Reputation: 978

I think the function you are missing here is find() http://www.cplusplus.com/reference/map/map/find/

Assuming you only want to find the distance between 1st two occurrences, I updated you code to the following,

#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;
}

Upvotes: 1

Related Questions