面試:C++輸入資料

來源:互聯網
上載者:User

標籤:leetcode   start   turn   i++   轉換   之間   總結   get   結束   

  最近在做筆試題,相比與leetcode,筆試題都是要自己寫輸入輸出的,每次在這裡都浪費了不少時間,這篇文章總結了一下在C++中怎麼向數組中輸入資料。

1. 先輸入數組大小,然後輸入資料資料,中間以空格或者‘\n‘字元隔開

 1 /* 2  * 兩種輸入方式 3  * 3  4  * 1 2 3  5  * 6  * 3  7  * 1 8  * 2 9  * 310  * 11  */12 vector<int> inputArray(){13     int size = 0;14     cin >> size;15     vector<int> inputs;16     for(int i=0;i<size;i++){17         int tmp;18         cin >> tmp;19         inputs.push_back(tmp);20     }21     return inputs;22 }

2、輸入以‘,‘字元分割的資料,思路將輸入儲存為字串,然後轉換為具體的資料

 1 // 1,2,3,4,5  2 vector<int> inputArray2(){ 3     string inputs; 4     cin >> inputs; 5     //split 6     vector<string> splits; 7     int start = 0; 8     for(size_t i=0;i<inputs.size();i++){ 9         if(inputs[i] == ‘,‘){10             splits.push_back(inputs.substr(start,i-start));11             start = i+1;12         }13     }14     if(start != (int)inputs.size()){15         splits.push_back(inputs.substr(start));16     }17     vector<int> res;18     for(string s:splits){19         res.push_back(std::stoi(s));20     }21     return res;22 }

3.輸入無限長度的資料,資料之間用空格分開,斷行符號結束

 1 // 輸入無限長度的數組 1 2 3 4 5 6 ... 2 vector<int> inputArray3(){ 3     vector<int> inputs; 4     int a; 5     do{ 6         cin >> a; 7         inputs.push_back(a); 8     }while(getchar() != ‘\n‘); 9     return inputs;10 11 }

4. 和方法1類似,輸入二維數組

 1 vector<vector<int>> inputMatrix(){ 2     int m,n; 3     cin >> m >> n; 4     vector<vector<int>> matrix(m,vector<int>(n,0)); 5     for(int i=0;i<m;i++){ 6         for(int j=0;j<n;j++){ 7             int a; 8             cin >> a; 9             matrix[i][j] = a;10         }11     }12     return matrix;13 }

 

面試:C++輸入資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.