从下面的代码中您可以看到 vector 数组具有相同的数字两次或以上。我想要做的是从指针 *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 中查找唯一的前两个相同元素?
更新
解决问题:
- 我总是想通过取消引用指针来知道同一元素的第一个和第二个位置的原因是,稍后我会做一些研究,并且在该研究中,我将获得一些与第一个和第二个相关的时间相同号码的位置。问题是,我想忽略第二次后仍然重复的相同元素,因为我想在计算中忽略这些元素位置。
- 例如,如果打印出代码,您将找到以下元素:** vector 元素为 1 8 2 2 2 5 7 7 7 7 8 **。在这种情况下,元素 2 的前两个位置是 [2] 和 [3],因此我想忽略位置 [4]。另一件要提到的事情是,我不在乎值或结果是否[我的意思是例如828或888,我会考虑两者]。例如,数字 8 位于位置 array[1] 和 [10] 中。我也会考虑这一点。
最佳答案
创建一个映射,其中每个值都存储为键,映射到索引列表:
std::unordered_map<int, std::vector<size_t>> indexMap;
循环初始值并填充 map :
for (size_t index = 0; index < ar.size(); index++)
{
indexMap[ar[index]].push_back(index);
}
现在,您可以循环遍历 map 并处理具有 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
是索引
。)
关于c++ - 如何仅考虑 *pointer 中的前两个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474149/