落書きノート

ふと自分が気になった事を書いてます

C++で問題を解く

#include <iostream>

using namespace std;

int ary_plus_cpy(int* a, const int* b, int n){
  int result_n = 0;

  while(n-- > 0){
    if(*b > 0){
      *a++ = *b;
      result_n++;
    }
    b++;
  }

  return result_n;
}

int main(void){
  const int n = 5;
  int result_n;
  int x[n],y[n];

  for(int i = 0; i < n; i++){
    cout << "y[" << i << "] = ";
    cin >> y[i];
  }

  result_n = ary_plus_cpy(x,y,n);

  cout << "正の要素を配列xにコピーしました。" << endl;

  for(int i = 0; i < result_n; i++){
    cout << "x[" << i << "] = " << x[i] << endl;
  }

  return 0;
}




#include <iostream>

using namespace std;

int search_idx(int* a, int* idx, int n, int key){
  int result_n = 0;

  for(int i = 0; i < n; i++){
    if(a[i] == key){
      idx[result_n] = i;
      result_n++;
    }
  }

  return result_n;
}

int main(void){
  const int n = 7;
  int a[n];
  int idx[n];
  int key;
  int result_n;

  for(int i = 0; i < n; i++){
    cout << "a[" << i << "] : ";
    cin >> a[i];
  }

  cout << "探索する値 : ";
  cin >> key;

  result_n = search_idx(a, idx, n, key);
  cout << "一致する要素は以下の" << result_n << "個です。" << endl;
  
  for(int i = 0; i < result_n; i++){
    cout << "a[" << idx[i] << "]" << endl;
  }

  return 0;
}




#include <iostream>

using namespace std;

int main(void){
  double* x1 = new double;
  double* x2 = new double();
  double* x3 = new double(0.0);

  cout << "x1 = " << *x1 << endl;
  cout << "x2 = " << *x2 << endl;
  cout << "x3 = " << *x3 << endl;

  delete x1;
  delete x2;
  delete x3;
  
  return 0;
}





#include <iostream>

using namespace std;

int main(void){
  int n;

  cout << "要素数 : ";
  cin >> n;

  double* a;

  try{
    a = new double[n];
  }catch(bad_alloc){
    cout << "配列の生成に失敗しました。" << endl;
    return 1;
  }

  for(int i = 0; i < n; i++){
    a[i] = i * 1.1;
    cout << "a[" << i << "] = " << a[i] << endl;
  }

  return 0;
}