string&vector閱讀小測試

看c++ primer,測試了幾條語法,保存一下代碼~
1.初始化string
注:字符串字面量不能直接相加

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int main(){
    string f5(5, 'f');
    string g5(5, 'g');
    //string test="hello"+"!"; 錯誤!字符串字面量不能直接相加
    string str1 = f5 + g5;
    string str2(g5 + f5);
    if (str1 > str2)
        cout << str1;
    else
        cout << str2;
    system("pause");
    return 0;
}

2.修改string中的值

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main(){
    string str("abc abc");
    for (decltype(str.size()) i = 0; i < str.size() &&
        !isspace(str[i]); i++)
        str[i] = toupper(str[i]);
    //運用range for語句改變str中的值時,記得把定義的變量設置爲引用,否則無用
    for (auto &c : str){
        c = tolower(c);
    }
    for (auto c : str){
        cout << c << " ";
    }
    system("pause");
    return 0;
}

3.初始化vector

#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;
typedef vector<int> vint;
typedef vector<char> vchar;
int main(){
    vint v{ 1, 2, 3 }; //輸出1 2 3
    vint v1(10); //輸出0 0 0...
    vint v2{ 10 };//輸出10
    vint v3(10, -1);//輸出-1 -1 -1...
    vint v4{ 10, -1 };//輸出10 -1
    vchar vc{ 'a' ,'b','c'};//輸出a b c

    vint v5;
    for (int i = 0; i < 5; i++)
        v5.push_back(i);//輸出0 1 2 3 4
    vint v6(5);//v6已經壓入5個0
    for (int i = 0; i < 5; i++)
        v6.push_back(5);//輸出0 0 0 0 0 5 5 5 5 5
    v5 = { 9, 9, 9 };//v5輸出9 9 9
    v6 = v5;//v6輸出9 9 9
    vint v7;
    /*v7爲空,此聲明嚴重錯誤,程序會崩
    for (int i = 0; i < 5; i++){
        v7[i] = i;
    }*/
    for (int t; cin>>t;v7.push_back(t));//自行初始化,ctrl+Z結束
    for (auto c : v7)
        cout << c << endl;
    //使用迭代器訪問,迭代器和!=是良配
    for (auto it = v7.begin(); it != v7.end(); ++it)
        cout << *it << " ";
    system("pause");
    return 0;
}
發佈了39 篇原創文章 · 獲贊 2 · 訪問量 8911
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章