如何查找数组中所有重复元素的位置

How to find the location for all repeated elements in array?

本文关键字:元素 位置 何查找 查找 数组      更新时间:2023-10-16

我可以对代码应用哪些更改以查找 EX 的每个重复元素的位置:12 或 45代码:

#include < iostream >
using namespace std;
int   findnumber ( int Array[]  ,  int keyword  , int size ){
    for  ( int y=0 ; y<size ; y++ )
        if  ( keyword==Array[y] ) {
            return y;
        }
    return -1; //not found
}
int main  ( ){
    int my_array[]={12,12,5,6,9,45,5,54,45};
    int searchinput;
    cout<<"please select number to search from these (12,12,5,6,9,45,5,54,45) : ";
    cin>>searchinput;
    int result. =  findnumber  (my_array , searchinput , 9);
    if(result>=0){
        cout<<"The number "<<my_array[result]<<" was found in index of : "<<result<<endl;
    }
    else
    {
    cout<<"The number "<<searchinput<<" was not found :( "<<endl;
    } 

解决方案

更新函数以返回索引向量而不是单个索引。一种方法是按如下方式定义它:

#include <vector>

vector<int> findnumber(int Array[], int keyword, int size) {
    vector<int> res;
    for (int y = 0; y < size; y++) {
        if (keyword == Array[y]) {
            res.push_back(y);
        }
    }
    return res; 
}

此外,应按如下方式修改函数调用和打印:

vector<int> result = findnumber(my_array, searchinput, 9);
if (result.size() > 0) {
    cout << "The number " << searchinput << " was found in the following indices : ";
    for (int i : result){
        cout << i << " ";
    }
    cout << endl;
}
else{
    cout << "The number " << searchinput << " was not found :( " << endl;
}

结果

input: 45
output: The number 45 was found in the following indices : 5 8
input: 12
output: The number 12 was found in the following indices : 0 1
input: 6
output: The number 6 was found in the following indices : 3
input: 7
output: The number 7 was not found :(

如果不允许使用向量,另一种解决方案是让你的函数接受开始和结束(大小(索引。并在 main 中执行 while 循环以开始使用返回的上一个索引 + 1 开始搜索。(请注意,这种技术可以经常与 STL 算法一起使用,例如 std::find (

int findnumber(int Array[], int keyword, int start, int size) {
    for (int y = start; y < size; y++) {  
        if (keyword == Array[y]) {
            return y;
        }
    }
    return -1; //not found    
}
int main() {
    int my_array[] = { 12,12,5,6,9,45,5,54,45 };
    int searchinput;
    cout << "please select number to search from these (12,12,5,6,9,45,5,54,45) : ";
    cin >> searchinput;
    int result = findnumber(my_array, searchinput, 0, 9);
    if (result >= 0) {
        while (result >= 0) {
            cout << "The number " << my_array[result] << " was found in index of : " << result << endl;
            result = findnumber(my_array, searchinput, result+1, 9);
        }
    } else {
        cout << "The number " << searchinput << " was not found :( " << endl;
    }
}

与其返回第一次出现,不如尝试将其添加到容器中,可能是列表或向量,您必须在进入循环之前创建它们,其中保存所有索引。最后,您可以返回此容器并在应用程序中使用它。

也许你看看这个:http://www.cplusplus.com/reference/stl/

我找到了一个简单的解决方案我可以将return y;更改为cout<<y<<endl;然后调用函数...就是这样