c++学习之路2

  • 1.结构体嵌套结构体

struct student
{
    string name;
    int age;
    int score;
    
};

struct teacher
{
    int number;
    string name;
    int age;
    struct student stu;

};

void print_struct(struct student* p) {
    cout << "学生姓名:" << p->name << endl
        << "学生分数:" << p->score << endl;
}

teacher t;
    t.name="老王";
    t.age = 28;
    t.number = 1;
    t.stu.name = "小王";
    t.stu.age = 10;
    t.stu.score = 100;

    cout << "老师的姓名:" << t.name << endl
        << "老师的年龄: " << t.age << endl
        << "老师的学生: " << t.stu.name << endl;

    print_struct(&t.stu);//地址传入

  • 2.获取字符串的第几个字符

#include <string>

string nameSeed="ABCDE";

void allocate(struct Teacher tArray[],int len){

        for(int i =0;i<len;i++){

                tArray[i].name = "Teacher_";

                tArray[i].name += nameSeed[i];//直接字符串nameSeed[i],就行

        }

}

  • 3.案例:根据结构体的年龄,使用冒泡排序:

#include <iostream>
using namespace std;
#include <string>

struct Hero
{
    string name;
    int age;
    string sex;
};

void sort_hero(struct Hero hero[],int len) {
    struct Hero h1;
    for (int i = 0;i<len-1;i++) {
        for (int j = 0;j<len-1-i;j++) {
            if (hero[j].age>hero[j+1].age) {
                h1 = hero[j];
                hero[j] = hero[j + 1];
                hero[j + 1] = h1;
            }
        }
    }
}

void print_info(struct Hero hero[], int len) {

    for (int i = 0;i<len;i++) {

        cout << "英雄人物:" << hero[i].name
            << " 英雄年龄:" << hero[i].age
            << " 英雄性别:" << hero[i].sex << endl;
    }
}


int main() {

    struct Hero hero[5] = {
        {"刘备",23,"男"},
        {"关羽",22,"男"},
        {"张飞",20,"男"},
        {"赵云",21,"男"},
        {"貂蝉",19,"女"}
    };
    int len = sizeof(hero) / sizeof(hero[0]);
    sort_hero(hero, len);

    print_info(hero,len);

    system("pause");
    return 0;
}

  • 4.c++清屏操作

system("pause");

system("cls");
 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值