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

时间:2018-04-16 18:23:38

标签: c++

我可以对代码应用哪些更改来查找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;
    } 

4 个答案:

答案 0 :(得分:1)

<强>解决方案

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

#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 :(

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

如果您不允许使用向量,则另一种解决方案是让您的函数接受开始和结束(大小)索引。并在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;
    }
}

答案 3 :(得分:0)

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