c++ - 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;
}
解决方案
我认为您在这里缺少的功能是 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;
}
推荐阅读
- scikit-learn - 如何修复 sklearn fit_transform 上的“元组索引超出范围”错误?
- string - 如何并行运行bash函数并将所有输出按顺序合并到一个字符串?
- python - 在 urllib.requests 中启用重定向
- cuda - 在 Inline PTX CUDA 中简单添加向量
- authentication - 授权0。如何获取用户的权限和角色?
- javascript - 如何使用已有的 bcrypt 代码实施护照?
- scala - 有两个具有相同寻址方案的不同 Map 的原因是什么?
- python - 为什么我收到错误:AtributeError: __enter__ when using requests.get() in `with` 语句
- svg - 为什么这个外部 SVG 渐变没有出现在本地 SVG 填充中?
- git - 检测 CodeCommit 中的更改并在 EC2 实例中运行命令