C++数组常用操作

1. 遍历数组

  • 使用基于范围的for循环来遍历整个数组
  • 用_countof()来得到数组中的元素个数
 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int main(){
 5     int arr[]={11,12,13,14,15};
 6     //_countof用于输出数组里面元素个数
 7     cout<<_countof(arr)<<endl;
 8     
 9     for(int i:arr){
10         //i 是指定访问的那个变量。存放数组里面的元素
11         cout<<"I am "<<i;
12         printf("
");
13     }
14     cout<<endl<<"end";
15     return 0;
16 }

2.字符串数组的输入

  • 常用cin.getline(name,MAX,' ')

cin 为 istream类的对象,调用getline函数。

  • name是该数组的名字
  • MAX是输入的字符最大个数
  • 最后的是结束的标志。

以下两个条件达到,将结束输入。

1. 达到MAX-1 2. 遇到最后的标志(常常是' ')

  • 用for循环来遍历数组
 1 #include <iostream>
 2 using namespace std;
 3 int main(){
 4     const int MAX=10;
 5     char c1[MAX];
 6     cout<<"What's your favourite subject?"<<endl;
 7     //从外设读取流,遇到'
'结束
 8     cin.getline(c1,MAX,'
');
 9     cout<<"Your favourite subject is "<<c1<<endl;
10     int counter(0);
11     for(auto i:c1){
12         //将从0遍历到MAX
13         cout<<(++counter)<<" : "<<i<<"	";
14     }
15     return 0;
16 }

3. 指针数组

 1  #include <iostream>
 2  using namespace std;
 3  int main(){
 4      //数组指针,数组中的五个元素,均指向一个char[]的串
 5     char *psubject[]={        
 6             "English",
 7             "Math",
 8             "Physics",
 9             "Chinese",
10             "Chemistry"
11     };
12     cout<<"Enter 1-5 to get a subject"<<endl;
13     int chooice;
14     cin>>chooice;
15     //psubject这个指针的第n个,为一个数组,可以直接输出
16     if(chooice>=1&&chooice<=5)
17         cout <<"what you chose is "<< psubject[chooice-1];
18     return 0;
19  }

4. sizeof

sizeof用于输出所占的字节。sizeof为一个「操作符」,得到的结果为无符整形。

1 int i=1;
2 cout<<sizeof i;

结果为4,因为int类型的 i 要占4个字节。

原文地址:https://www.cnblogs.com/heenhui2016/p/6007720.html