c++學習拾遺【一】

來源:互聯網
上載者:User

字串

1.幾個特殊的資料類型

 

string s(“Hello”);
s.size()==6   string::size_type (unsigned type)

 

 

int *p1,*p2;
ptrdiff_t   n = p1 – p2;  //指標的差
#include<cstddef>
ptrdiff_t (signed int)

 

 

vector 下標類型 vector::size_type

string 下標類型 string::size_type

數組下標類型   size_t 

 

2.字串與數組 

string s1,s2=”Hello”; 
s1 = s2;    // 字串可以直接賦值
int ia[] = {0, 1, 2}; 
int ia2[3];
ia2 = ia;   //數組不可以

 

 

3.動態數組

size_t n = get_size();    //允許動態分配空數組 get_size()運行時才知道值
int* p = new int[ n];
 
string *psa = new string[10];  //string不是內建類型,分配了記憶體,初始化了元素
int *pia = new int[10];        //int是內建類型,分配了記憶體,不初始化元素 (所以const類型時則有錯)
int *pia = new int[10]();      // 強制要求編譯器初始化

 

 

4.C風格字串

#include<cstdlib> 
int *pi = NULL;  // NULL是C 風格

 

 

#incldue<cstring>
strlen(s) strcmp(s1,s2)….
char ca[] = {‘c’, ‘+’, ‘+’};
strlen(ca);//危險 strlen根據字串結束符null來判斷結尾

 

 

5.const與指標 

C++強制要求指向const對象的指標也必須具有const特性,但允許把非const對象的地址賦給指向const對象的指標。

const double pi = 3.14;
double *ptr = &pi; //錯誤
 
double dval = 3.14;
const double *cptr;
cptr = &dval //正確 所以可以個性const指標指向對象的值

 

  

6.自增操作區別

i ++; // 需要儲存原來的i值
++ i; // 所做的工作更少

 

 

vector<int> ivec;
int cnt = 10;
while(cnt>0)
   ivec.pust_back(cnt--);
vector<int>::iterator iter = ivec.begin();
while(iter != ivec.end())
cout << *iter++ <<endl;              // *iter++ ó *(iter++)

 

 

7.箭頭操作符 ->

C++為在點操作符後使用的解引用操作定義的同義字.

(*p).foo;  ó   p->foo;

 

8.sizeof操作符

對數組進行sizeof操作等效於將對其元素類型做sizeof操作的結果乘上數組元素的個數

int sz = sizeof(ia)/sizeof(*ia);//取數組元素個數 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.