从下面的代码中,您可以看到向量数组具有相同的数目两倍或更多。我要做的是从指针* ptr
中找到前两个相同数字的位置 #include<iostream>
#include<iterator> // for iterators
#include<vector> // for vectors
using namespace std;
int main()
{
vector<int> ar = { 1,8,2, 2, 2, 5,7,7,7,7,8 };
// Declaring iterator to a vector
vector<int>::iterator ptr;
// Displaying vector elements using begin() and end()
cout << "The vector elements are : ";
for (ptr = ar.begin(); ptr < ar.end(); ptr++)
cout << *ptr << " ";
return 0;
}
让我们假设我想通过取消引用指针* ptr来打印出7的前两个位置和元素。我应该使用if这样的条件吗?
int *array = ptr.data();
for( int i =0; i < ar.size(); i++) {
if( array[i] - array[i+1]+ ==0)
cout<<array[i]<<endl;
}
但是我如何保证它不会从* ptr中查找仅前两个相同的元素?
更新
解决问题:
答案 0 :(得分:2)
创建一个映射,其中每个值都作为键存储,并映射到索引列表:
std::unordered_map<int, std::vector<size_t>> indexMap;
查看初始值并填写地图:
for (size_t index = 0; index < ar.size(); index++)
{
indexMap[ar[index]].push_back(index);
}
现在,您可以遍历地图并处理具有2个或多个索引的每个值,并且仅将前2个索引用于您要执行的操作:
for (auto const& [value, indices] : indexMap)
{
if (indices.size() < 2)
continue;
size_t firstIndex = indices[0];
size_t secondIndex = indices[1];
// do whatever
}
(如果您不使用C ++ 17或更高版本,请使用for (auto const& pair : indexMap)
,其中pair.first
是value
,而pair.second
是{{1} }。)
答案 1 :(得分:1)
您可以使用map
或unordered_map
注册每个值的索引。
以下是该概念的简单演示:
#include<iostream>
#include<vector>
#include<map>
using namespace std;
int main() {
vector<int> ar{ 1, 8, 2, 2, 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;
}
输出:
1: 0
2: 2 3 4
5: 5
7: 6 7 8 9
8: 1 10