string&vector阅读小测试

本文通过几个实例展示了C++中字符串(string)的基本操作,包括初始化、拼接及字符修改;同时也介绍了向量(vector)的多种初始化方式及元素添加等基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值