鍦ㄧ紪绋嬬殑涓栫晫閲岋紝鏁扮粍鏄竴绉嶉潪甯稿熀纭€鐨勫鍣紝涓撻棬鐢ㄤ簬瀛樺偍涓€绯诲垪鐩稿悓绫诲瀷鐨勫厓绱犮€傝繖浜涘厓绱犲湪璁$畻鏈哄唴瀛樹腑杩炵画鎺掑垪锛屼娇寰楅泦鍚堟暟鎹殑瀛樺彇鍜屾搷浣滃彉寰楅潪甯搁珮鏁堛€傛暟缁勭殑鐢ㄩ€斿箍娉涳紝浠庣畝鍗曠殑鏁版嵁鏀堕泦鍒板鏉傜殑绠楁硶瀹炵幇锛岄兘鏄瀯寤洪珮鏁堢▼搴忕殑鍏抽敭瑕佺礌銆?/p>
瑕佸0鏄庝竴涓暟缁勶紝浣犻渶瑕佹寚瀹氬厓绱犵殑绫诲瀷鍜屾暟閲忋€備緥濡傦紝浣犲彲浠ュ0鏄庝竴涓寘鍚?0涓暣鏁扮殑鏁扮粍濡備笅锛?/p>
int myArray[10];
鍒濆鍖栨暟缁勬椂锛屼綘鍙互涓哄叾鎸囧畾鍏蜂綋鐨勫€笺€備緥濡傦細
int myArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
濡傛灉鎻愪緵鐨勫垵濮嬪€煎皯浜庢暟缁勭殑澶у皬锛屾湭鍒濆鍖栫殑閮ㄥ垎灏嗛粯璁や负0锛?/p>
int myArray[10] = {1, 2, 3};
鏁扮粍鐨勫厓绱犻€氳繃涓嬫爣杩涜璁块棶锛屼笅鏍囦粠0寮€濮嬶紝鍒版暟缁勫ぇ灏忓噺1缁撴潫銆備緥濡傦細
int myArray[5]; myArray[0] = 10; //璁剧疆绗竴涓厓绱犱负10
int firstElement = myArray[0]; //璁块棶骞朵娇鐢ㄧ涓€涓厓绱?/p>
瀵逛簬鍔ㄦ€佸垱寤虹殑鏁扮粍锛屼綘闇€瑕佷娇鐢╪ew鎿嶄綔绗︽潵鍒嗛厤鍐呭瓨锛屽苟閫氳繃鎸囬拡鏉ユ搷浣滃厓绱狅細
int dynamicArray = new int[5]; dynamicArray[0] = 42;
int& secondElement = dynamicArray[1]; //浣跨敤寮曠敤璁块棶鍏冪礌
褰撴秹鍙婂埌鍥哄畾灏哄鐨勬暟缁勬椂锛屼竴鏃﹀湪澹版槑鏃剁‘瀹氫簡澶у皬锛屽氨鏃犳硶鍦ㄨ繍琛屾椂鏇存敼锛?/p>
const int size = 10; int fixedArray[size] = {1, 2, 3, 鈥? 10};
鍔ㄦ€佸垱寤烘暟缁勫垯鑳藉閫傚簲涓嶅悓鐨勬暟鎹噺闇€姹傦紝閫氳繃new鍜宒elete鏉ョ鐞嗗唴瀛橈細
int dynamicArray = new int[10]; //鍒嗛厤鍐呭瓨 delete[] dynamicArray; //鍒犻櫎鍐呭瓨
鏁扮粍鐨勭被鍨嬭浆鎹㈡妧宸т富瑕佺敤浜庡疄鐜版暟鎹殑澶嶅埗鎴栦紶閫掋€備緥濡傦紝浣犲彲浠ヤ娇鐢╩emcpy鍑芥暟鏉ュ鍒舵暟缁勬暟鎹細
int firstArray = new int[5]; int secondArray[5]; memcpy(secondArray, firstArray, sizeof(secondArray)); //澶嶅埗鏁版嵁
鍦ㄥ疄闄呭簲鐢ㄤ腑锛岃繕鏈夎澶氬叧浜庢暟缁勬搷浣滅殑鎶€宸с€備緥濡傦紝浣犲彲浠ヤ娇鐢ㄥ惊鐜潵閬嶅巻鏁扮粍骞惰緭鍑哄厓绱狅細
for (int i = 0; i < 5; ++i) { std::cout << myArray[i] << " "; }
---
鏁扮粍璁块棶鏁堢巼鎻愬崌涓庤秺鐣岄伩鍏嶇瓥鐣?/p>
涓€銆佹彁楂樻暟缁勮闂晥鐜?/h3>
鍦ㄧ紪绋嬩腑锛屼娇鐢ㄦ寚閽堢洿鎺ヨ闂暟缁勫厓绱狅紝鍙互璺宠繃鏁扮粍涓嬫爣鎿嶄綔鐨勫紑閿€锛屼粠鑰屾彁楂樻€ц兘銆傝繖绉嶆柟娉曡兘澶熸洿鐩存帴鍦版搷浣滃唴瀛橈紝鍑忓皯璁$畻灞傜骇锛岃繘鑰屾彁鍗囨墽琛岄€熷害銆?/p>
浜屻€侀伩鍏嶆暟缁勮秺鐣岀殑甯歌鎶€宸?/h3>
鍦ㄨ闂暟缁勫墠锛屽姟蹇呴獙璇佺储寮曞€兼槸鍚﹀湪鏈夋晥鑼冨洿鍐呫€備竴涓畝鍗曠殑妫€鏌ユ柟娉曟槸纭繚绱㈠紩鍊奸潪璐熶笖灏忎簬鏁扮粍澶у皬銆傝繖鏍凤紝鎴戜滑鍙互閬垮厤鍥犵储寮曢敊璇鑷寸殑绋嬪簭宕╂簝鎴栨湭瀹氫箟琛屼负銆?/p>
```cpp
if (index >= 0 && index < size) { // 瀹夊叏璁块棶鏁扮粍}
```
涓夈€佸疄鎴樻渚嬩笌浠g爜绀轰緥 馃洜锔?/h3>
3.1 鏁扮粍鍦ㄥ疄闄呴」鐩腑鐨勫簲鐢?/p>
璁╂垜浠€氳繃涓€涓畝鍗曠殑璁$畻鍣ㄧ▼搴忔潵灞曠ず鏁扮粍鐨勫簲鐢ㄣ€傜▼搴忎腑锛屾垜浠娇鐢ㄤ簡鏁扮粍鏉ュ瓨鍌ㄦ暟瀛﹀父鏁帮紝濡傁€鍜屾鎷夋暟銆?/p>
```cpp
const double pi = 3.14159;
const double euler = 2.71828;
// ...鍏朵粬浠g爜浣跨敤鏁扮粍杩涜鎿嶄綔
```
3.2 浠g爜绀轰緥涓庤皟璇曟寚瀵?/p>
杩欓噷鏈変竴涓娇鐢ㄥ啋娉℃帓搴忕畻娉曞鏁扮粍杩涜鎺掑簭鐨勭ず渚嬨€傞€氳繃杩欎釜绀轰緥锛屼綘鍙互浜嗚В濡備綍缂栧啓銆佽皟璇曞苟浼樺寲浠g爜銆?/p>
```cpp
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
std::swap(arr[j], arr[j+1]);
}
// ...鍏朵粬浠g爜杩涜鎺掑簭鎿嶄綔鍙婅皟璇?/p>
```
鍥涖€佺粌涔犻涓庨」鐩缓璁?/h3>
寤鸿浣犵粌涔犵紪鍐欏疄鐜板揩閫熸帓搴忕畻娉曠殑浠g爜锛屽苟涓庨€夋嫨鎺掑簭杩涜鎬ц兘姣旇緝銆傚畬鎴愯繖涓换鍔★紝浣犻渶瑕佸疄鐜板揩閫熸帓搴忕畻娉曪紝骞跺鍏惰繘琛屾€ц兘娴嬭瘯锛屼互姣旇緝鍏朵笌閫夋嫨鎺掑簭鍦ㄤ笉鍚屾暟鎹妯′笅鐨勮〃鐜般€?/p>
浠诲姟锛氬疄鐜板揩閫熸帓搴忕畻娉曪紝骞跺湪涓嶅悓鏁版嵁瑙勬ā涓嬫祴璇曞叾鎬ц兘銆?/p>
寤鸿锛氬埄鐢ㄨ緭鍏ヨ緭鍑烘祦璁板綍鏁版嵁鎺掑簭鍓嶅悗鐨勭姸鎬侊紝瀵规瘮涓嶅悓鎺掑簭绠楁硶鐨勬€ц兘宸紓銆傞€氳繃杩欑鏂瑰紡锛屼綘灏嗘洿娣卞叆鍦扮悊瑙f暟缁勫湪C++缂栫▼涓殑浣跨敤鍜屼紭鍖栨妧宸э紝涓哄涔犳洿澶嶆潅鐨勭畻娉曞拰鏁版嵁缁撴瀯鎵撲笅鍧氬疄鐨勫熀纭€銆?/p>
閫氳繃浠ヤ笂鐨勫涔犲拰瀹炶返锛屼綘灏嗛€愭鎺屾彙鏁扮粍鎿嶄綔鐨勯珮绾ф妧宸э紝涓虹紪绋嬩箣璺坊鐮栧姞鐡︺€?/p> |