如何搜索数组的元素?

时间:2018-01-13 13:32:54

标签: c++

我的arrray看起来像 int myarray [] = {6,5,2,6,7,8,6}; 我想要我的节目说 如果用户输入了'
"你的号码在0,3,6和#34;被发现3次。 如果找不到说'#34;找不到"。

这是我的努力:

#include <iostream>
using namespace std;
int main() {
  bool flag=false;
  int x[]={9,11,6,7,6,4,6};
  int count=0;
  int n,i,j,c;
  cout<<"What number do you want to search : ";
  cin >>n;
  for(int i=0;i<7;i++){
    if(x[i]==n){ 
      count++; 
      flag=true; 
    } 
  } 
  if(flag){ 
    cout <<n<<" is found "<<count<<" times in :"; 
    for(int i=0;i<7;i++){ 
      if(x[i]==n) cout <<i<<','; 
     } 
   } else { 
     cout <<n<<" is not found"<<endl; 
   } 
} 

2 个答案:

答案 0 :(得分:-1)

这是一个开始的例子:

Found value 6 at position 0
Found value 6 at position 3
Found value 6 at position 6

当用户输入6时,将输出:

i

如果要匹配与问题中输出完全相同的输出,可以存储索引(例如,std::vector中的所有$scope.takePhoto = function () { var options = { quality: 100, destinationType: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.CAMERA, allowEdit: true, encodingType: Camera.EncodingType.JPEG, targetWidth: 300, targetHeight: 300, popoverOptions: CameraPopoverOptions, saveToPhotoAlbum: true }; $cordovaCamera.getPicture(options).then(function (imageData) { $rootScope.imgURI = "data:image/jpeg;base64," + imageData; $state.go('menu.signUp'); }, function (err) { // An error occured. Show a message to the user }); } ),然后打印它们。< / p>

答案 1 :(得分:-2)

这是在数组中搜索元素的代码。这种方法是线性搜索

   public class SignUpActivity extends AppCompatActivity {

    String TAG = SignUpActivity.class.getSimpleName();
    String URL;

    ArrayList<String> countries = new ArrayList<>();

    String jsonStr="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);

        String response = new MyClass.execute();


    }

    private class MyClass extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //TODP
        }

        @Override
        protected String doInBackground(Void... params) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(URL, "GET");
            //Handling response in jsonStr code 
            return jsonStr;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //TODO
            jsonStr = result;
        }

    }
}