日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++数组常用操作

發(fā)布時間:2023/12/18 c/c++ 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++数组常用操作 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1. 遍歷數(shù)組

  • 使用基于范圍的for循環(huán)來遍歷整個數(shù)組
  • 用_countof()來得到數(shù)組中的元素個數(shù)
1 #include <iostream> 2 #include <cstdio> 3 using namespace std; 4 int main(){ 5 int arr[]={11,12,13,14,15}; 6 //_countof用于輸出數(shù)組里面元素個數(shù) 7 cout<<_countof(arr)<<endl; 8 9 for(int i:arr){ 10 //i 是指定訪問的那個變量。存放數(shù)組里面的元素 11 cout<<"I am "<<i; 12 printf("\n"); 13 } 14 cout<<endl<<"end"; 15 return 0; 16 }

2.字符串數(shù)組的輸入

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

cin 為 istream類的對象,調用getline函數(shù)。

  • name是該數(shù)組的名字
  • MAX是輸入的字符最大個數(shù)
  • 最后的是結束的標志。

以下兩個條件達到,將結束輸入。

1. 達到MAX-1 2. 遇到最后的標志(常常是'\n')

  • 用for循環(huán)來遍歷數(shù)組
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 //從外設讀取流,遇到'\n'結束 8 cin.getline(c1,MAX,'\n'); 9 cout<<"Your favourite subject is "<<c1<<endl; 10 int counter(0); 11 for(auto i:c1){ 12 //將從0遍歷到MAX 13 cout<<(++counter)<<" : "<<i<<"\t"; 14 } 15 return 0; 16 }

3. 指針數(shù)組

1 #include <iostream> 2 using namespace std; 3 int main(){ 4 //數(shù)組指針,數(shù)組中的五個元素,均指向一個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個,為一個數(shù)組,可以直接輸出 16 if(chooice>=1&&chooice<=5) 17 cout <<"what you chose is "<< psubject[chooice-1]; 18 return 0; 19 }

4. sizeof

sizeof用于輸出所占的字節(jié)。sizeof為一個「操作符」,得到的結果為無符整形。

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

結果為4,因為int類型的 i 要占4個字節(jié)。

轉載于:https://www.cnblogs.com/heenhui2016/p/6007720.html

總結

以上是生活随笔為你收集整理的C++数组常用操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。