gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:02:29 24 4
gpt4 key购买 nike

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

最佳答案

解决方案

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

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

关于c++ - 如何找到数组中所有重复元素的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49863915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com