如何仅考虑* pointer中的前两个元素 [英] How to consider only first two elements from *pointer
问题描述
从下面的代码中,您可以看到向量数组具有相同的数目两倍或更多.我想做的是从指针* ptr
From the below code you can see that the vector array has the same number twice or more than. What I want to do is to find the first two same number's position from the pointer *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这样的条件吗?
Let's assume I want to print out the first two position and elements of 7 by dereferencing the pointer *ptr. Should I use an if a condition like
int *array = ptr.data();
for( int i =0; i < ar.size(); i++) {
if( array[i] - array[i+1]+ ==0)
cout<<array[i]<<endl;
}
但是我如何保证它不从* ptr中查找仅前两个相同的元素?
But how would I guarantee that it is not looking for the only first two same elements from *ptr?
更新
解决问题:
- 我一直想通过解引用指针来知道同一元素的第一和第二位置的原因是,稍后我将进行一些研究,并且在该研究中,我将获得与第一和第二位置相关的时间相同数字的位置.问题是,我想忽略第二次以后仍然重复的相同元素,因为我想在计算中忽略这些元素的位置.
- 例如,如果您打印出代码,则会发现以下元素:**矢量元素为1 8 2 2 2 5 7 7 7 7 8 **.在这种情况下,元素2的前两个位置是[2]和[3],因此我想忽略位置[4].还要提及的另一件事是,我不在乎值的大小或结果的大小与否[我的意思是例如828或888,我会同时考虑两者].例如,数字8在位置数组[1]和[10]中.我也会考虑这一点.
推荐答案
您可以使用map
或unordered_map
注册每个值的索引.
You could use map
or unordered_map
to register indexes of each value.
这是该概念的简单演示:
Here's a simple demo of the concept:
#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
这篇关于如何仅考虑* pointer中的前两个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!