C++ 如何仅从*指针中考虑前两个元素

C++ 如何仅从*指针中考虑前两个元素,c++,pointers,C++,Pointers,从下面的代码中,您可以看到向量数组具有相同数字的两倍或两倍以上。我想做的是从指针*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,

从下面的代码中,您可以看到向量数组具有相同数字的两倍或两倍以上。我想做的是从指针*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;     
}
#包括
#迭代器的include//
#包含//用于向量
使用名称空间std;
int main()
{ 
向量ar={1,8,2,2,2,5,7,7,7,8};
//将迭代器声明为向量
向量::迭代器ptr;
//使用begin()和end()显示矢量元素

cout您可以使用
映射
无序映射
来注册每个值的索引

以下是该概念的简单演示:

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

创建一个映射,其中每个值存储为键,映射到索引列表:

std::unordered_map<int, std::vector<size_t>> indexMap;
std::无序映射索引映射;
在初始值上循环并填充地图:

for (size_t index = 0; index < ar.size(); index++)
{
    indexMap[ar[index]].push_back(index);
}
for(size_t index=0;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
}
for(auto const&[value,index]:indexMap)
{
if(index.size()<2)
继续;
size_t firstIndex=索引[0];
size_t secondIndex=索引[1];
//做任何事
}

(如果您不使用C++17或更高版本,请使用
for(auto const&pair:indexMap)
,其中
对。第一个
对。第二个
索引

您能进一步澄清这个问题吗?我已经更新了这个问题,您是否对随后的重复值感兴趣(如[2 2])?根据您的评论,我假设只应报告后续的重复值(因此在本例中,不应报告第二次出现的2[2 8 2])。如果相同的值在向量中重复多次(如[2 2 8 2 2 2 2]),该怎么办?这是一个很好的观点,Martin。我已经更新了问题。数字不必是连续的。我唯一关心的是数字在数组中是否重复,并找到相同数字的前两个位置。与您的问题无关,但仍然很重要:假设我要打印数字2的第二个位置,应该是2.怎么做?@zero_field
除了在初始值中应该使用什么以外,我能理解逻辑吗?这里:
indexMap[value]。push_back(index);
for (auto const& [value, indices] : indexMap)
{
    if (indices.size() < 2)
        continue;

    size_t firstIndex = indices[0];
    size_t secondIndex = indices[1];

    // do whatever
}