C++ primer 练习题
生活随笔
收集整理的這篇文章主要介紹了
C++ primer 练习题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
練習3.32
數組實現
#include<iostream> #include<string> using namespace std; int main() { const int sz=10;int ia[sz],ib[sz];for (int i = 0; i < 10; i++)ia[i] = i;for (int j=0; j < 10; j++)//不能直接對數組使用復制運算符,需要逐一拷貝ib[j] = ia[j];for (auto val : ib)cout << val << " ";return 0; }vector實現
#include<iostream> #include<vector>using namespace std; int main() {const int sz=10;vector<int>v1, v2;for (int i = 0; i < sz; i++)v1.push_back(i);for (int j = 0; j < sz; j++)v2.push_back(v1[j]);for (auto val : v2)cout << val << " ";cout << endl;return 0;system("pause");}練習3.35:編寫一段程序,利用指針將數組中的元素置為0。
#include<iostream> #include<string> using namespace std; int main() { const int sz = 10;int a[sz], i = 0;for (i = 0; i < sz; i++)a[i] = i;int *p = begin(a);//令p指向a的首地址while (p != end(a)){*p = 0;p++;}for (auto val : a)cout << val << " ";return 0; }練習3.36:編寫一段程序,比較兩個數組是否相等。再寫一段程序,比較兩個vector對象是否相等。
【出題思路】
無論對比兩個數組是否相等還是兩個vector對象是否相等,都必須逐一比較其元素。
【解答】
對比兩個數組是否相等的程序如下所示,因為長度不等的數組一定不相等,并且數組的維度一開始就要確定,所以為了簡化起見,程序中設定兩個待比較的數組維度一致,僅比較對應的元素是否相等。
該例類似于一個彩票游戲,先由程序隨機選出5個0~9的數字,此過程類似于搖獎;再由用戶手動輸入5個猜測的數字,類似于購買彩票;分別把兩組數字存入數組a和b,然后逐一比對兩個數組的元素;一旦有數字不一致,則告知用戶猜測錯誤,只有當兩個數組的所有元素都相等時,判定數組相等,即用戶猜測正確。
數組實現
#include<iostream> #include<string> #include<ctime> //#include<vector> using namespace std; int main() { const int sz = 5;int a[sz], b[sz], i;srand((unsigned)time(NULL));for (i = 0; i < sz; i++)a[i] = rand() % 10;cout << "請輸入猜測的5個數字" << endl;int val;for (i = 0; i < sz; i++)if (cin >> val)b[i] = val;cout << "隨機數字是:" << endl;for (auto x : a)cout << x << " ";cout << "你猜的是:" << endl;for (auto x : b)cout << x << " ";cout << endl;int *p = begin(a), *q = begin(b);while (p != end(a) && q != end(b)){if (*p != *q){cout << "you are wrong" << endl;return -1;}p++;q++;}return 0; }vector實現
#include<iostream> #include<string> #include<ctime> #include<vector> #include<cstdlib> using namespace std; int main() { const int sz = 5;vector<int>v1, v2;srand((unsigned)time(NULL));for (int i = 0; i < sz; i++)v1.push_back(rand() % 10);cout << "請輸入猜測的5個數字" << endl;int val;for (int i = 0; i < sz; i++)if (cin >> val)v2.push_back(val);cout << "隨機數字是:" << endl;for (auto x : v1)cout << x << " ";cout << "你猜的是:" << endl;for (auto x : v2)cout << x << " ";cout << endl;auto it1 = v1.cbegin(), it2 = v2.cbegin();while (it1 != v1.cend() && it2 !=v2.cend()){if (*it1 != *it2){cout << "you are wrong" << endl;return -1;}it1++;it2++;}return 0; }練習3.40:編寫一段程序,定義兩個字符數組并用字符串字面值初始化它們;接著再定義一個字符數組存放前兩個數組連接后的結果。使用strcpy和strcat把前兩個數組的內容拷貝到第三個數組中。
#include<iostream> #include<string> #include<cstring> using namespace std; int main() { const char str1[] = "Welcome to ";const char str2[] = "C++ family ";//利用strlen函數計算兩個字符串的長度,并求結果字符串的長度char ret[strlen(str1) + strlen(str2) - 1];strcpy(ret, str1);strcat(ret, str2);cout << ret << endl;return 0; }但是函數編譯的時候會出現錯誤,不知道怎么回事
總結
以上是生活随笔為你收集整理的C++ primer 练习题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wxpython控件字体_wxPytho
- 下一篇: QT字体大全