首页 > 编程语言 >实验四 现代C++标准库类与模板

实验四 现代C++标准库类与模板

时间:2023-11-30 23:55:23浏览次数:53  
标签:库类 std string C++ cpp using include 模板 cout

实验任务1

task1.cpp源码

task1_1.cpp:

#include <iostream>

using std::cout;
using std::endl;

//类A的定义
class A {
public:
    A(int x0, int y0) : x{ x0 }, y{ y0 } {}
    void show() const { cout << x << "," << y << endl; }
private:
    int x, y;
};

//类B的定义
class B {
public:
    B(double x0, double y0) : x{ x0 }, y{ y0 } {}
    void show() const { cout << x << "," << y << endl; }
private:
    double x, y;
};

void test() {
    A a(3, 4);
    a.show();

    B b(3.2, 5.6);
    b.show();
}

int main() {
    test();
}
View Code

运行结果:

 task1_2.cpp:

#include <iostream>
#include <string>

using std::cout;
using std::endl;

//定义模板类X
template<typename T>
class X {
public:
    X(T x0, T y0) :x{ x0 }, y{ y0 } {}
    void show() const { cout << x << "," << y << endl; }
private:
    T x, y;
};

void test() {
    cout << "测试1:模板类抽象类型T用int实例化" << endl;
    X<int> x1(3, 4);
    x1.show();

    cout << "\n测试2:模板类抽象类型T用double实例化" << endl;
    X<double> x2(3.2, 5.6);
    x2.show();

    cout << "\n测试3:模板类抽象类型T用标准库中的string实例化" << endl;
    X<std::string> x3("hello", "c plus plus");
    x3.show();
}

int main() {
    test();
}
View Code 运行结果:

 

task2.cpp源码

task2_1,.cpp:

#include <iostream>
#include <string>
#include <limits>

using namespace std;

int main() {


    const int n = 10;
    string prompt = string(n, '*') + "Enter a string: " + string(n, '*') + '\n';

    cout << "测试1:";
    cout << prompt;
    string s1;
    cin >> s1;  //从输入流中提取字符串给s1,碰到空格、回车、Tab键即结束
    cout << "s1: " << s1 << endl;
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); //清空缓冲区

    cout << "\n测试2: ";
    cout << prompt;
    getline(cin, s1);  //从输入流中提取字符串给s1,直到换行
    cout << "s1: " << s1 << endl;

    cout << "\n测试3:";
    string s2, s3;
    cout << prompt;
    getline(cin, s2, ' ');  //从输入流中提取字符串给s2,直到换行
    getline(cin, s3);
    cout << "s2: " << s2 << endl;
    cout << "s3: " << s3 << endl;
}
View Code

运行结果:

 task2_2.cpp:

#include <iostream>
#include <string>

int main() {
    using namespace std;

    string s;

    cout << "Enter words: \n";
    //重复录入字符串,将小写字符转换为大写,直到按下ctrl+z
    while (getline(cin, s)) {
        for (auto& ch : s)
            ch = toupper(ch);
        cout << s << "\n";
    }
}
View Code

运行结果:

 task2_3.cpp:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    using namespace std;

    string s1;

    cout << "Enter words: \n";
    getline(cin, s1);
    cout << "original words: \n";
    cout << s1 << endl;
    cout << "to uppercase: \n";
    transform(s1.begin(), s1.end(), s1.begin(), ::toupper);
    cout << s1 << endl;
}
View Code

运行结果:

 task2_4.cpp:

#include <iostream>
#include <string>

int main() {
    using namespace std;

    string s1, s2;
    s1 = "nuist";
    s1[0] = 'N';
    s1.at(1) = 'U';
    cout << boolalpha << (s1 == "nuist") << endl;
    cout << s1.length() << endl;
    cout << s1.size() << endl;
    s2 = s1 + ", 2050";
    cout << s2 << endl;

    string email{ "[email protected]" };
    auto pos = email.find("@");
    if (pos == string::npos)
        cout << "illegal email address";
    else {
        auto s1 = email.substr(0, pos);
        auto s2 = email.substr(pos + 1);
        cout << s1 << endl;
        cout << s2 << endl;
    }

    string phone{ "15216982937" };
    cout << phone.replace(3, 5, string(5, '*')) << endl;

    string s3{ "cosmos" }, s4{ "galaxy" };
    cout << "s3: " + s3 + "s4: " + s4 << endl;
    s3.swap(s4);
    cout << "s3: " + s3 + "s4: " + s4 << endl;

    string s5{ "abc" };
    const char* pstr = s5.c_str();
    cout << pstr << endl;

    string s6{ "12306" };
    int x1 = stoi(s6);
    cout << x1 << endl;

    int x2 = 12306;
    string s7 = to_string(x2);
    cout << s7 << endl;

    double x3 = 123.06;
    string s8 = to_string(x3);
    cout << s8 << endl;
}
View Code

运行结果:

 

task3.cpp源码

task3_1.cpp:

#include <iostream>
#include <vector>


template<typename T>
void output(const T& obj) {
    for (auto& item : obj)
        std::cout << item << ",";
    std::cout << "\b\b \n";
}

int main() {
    using namespace std;

    vector<int> v1;
    vector<int> v2(5);
    vector<int> v3(5, 42);
    vector<int> v4{ 1, 9, 8, 4 };
    vector<int> v5{ v4 };

    output(v2);
    output(v3);
    output(v4);
    output(v5);
}
View Code

运行结果:

 task3_2.cpp:

#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

void output(const vector<int>& v) {
    cout << "v.size() = " << v.size() << endl;
    cout << "v.capacity() = " << v.capacity() << endl;
    cout << endl;
}

int main() {
    vector<int> v{ 42 };
    output(v);

    v.push_back(55);
    v.push_back(90);
    output(v);

    for (auto i = 0; i < 8; i++)
        v.push_back(i);
    output(v);

    v.pop_back();
    output(v);
}
View Code

运行结果:

 

task4.cpp源码

task4.cpp:

#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <algorithm>

using namespace std;

// 函数模板
// 通过索引方式输出对象值
template<typename T>
void output1(const T& obj) {
    for (auto i = 0; i < obj.size(); ++i)
        cout << obj.at(i) << ", ";
    cout << "\b\b \n";
}

// 函数模板
// 通过迭代器方式输出对象值
template<typename T>
void output2(const T& obj) {
    for (auto p = obj.cbegin(); p != obj.cend(); ++p)
        cout << *p << ", ";
    cout << "\b\b \n";
}

// 函数模板
// 通过auto for方式输出对象值
template<typename T>
void output3(const T& obj) {
    for (auto& item : obj)
        cout << item << ", ";
    cout << "\b\b \n";
}

// 测试string类对象
void test1() {
    string s1{ "cplus" };

    output1(s1);

    reverse(s1.begin(), s1.end());  // 对对象s1中的数据项进行翻转
    output2(s1);

    sort(s1.begin(), s1.end());   // 对对象s1中的数据项排序(默认升序)
    output3(s1);
}

// 测试array<int>类对象
void test2() {
    array< array<int, 4>, 3> x{ 1, 9, 8, 4, 2, 0, 2, 3, 2, 0, 4, 9 };

    output1(x.at(0));
    output2(x.at(1));
    output3(x.at(2));
}

// 测试vector<string>类对象
void test3() {
    vector<string> v1{ "Sheldon", "Leonard", "Howard", "Raj" };

    v1.push_back("Penny");
    v1.push_back("Amy");

    output1(v1);

    sort(v1.begin(), v1.end(), std::greater<string>());  // 对v1对象中的字符串按降序排序
    output2(v1);

    reverse(v1.begin(), v1.end());  // 对v1对象中的字符串翻转
    output3(v1);
}

int main() {
    cout << "测试1: " << endl;
    test1();

    cout << "测试2: " << endl;
    test2();

    cout << "测试3: " << endl;
    test3();
}
View Code

运行结果:

 

task5.cpp源码

textcoder.hpp:

#include<iostream>
#include<string>

using std::string;

class TextCoder {
private:
    string text;
    void encoder(){
        for (char& c : text) {
            if (isalpha(c)) {
                if (islower(c)) {
                       c = ((c - 'a' + 7) % 26) + 'a';
                } else {
                    c = ((c - 'A' + 7) % 26) + 'A';
                }
            }
        }
    }
        void decoder(){
        for (char& c : text) {
            if (isalpha(c)) {
                if (islower(c)) {
                       c = ((c - 'a' - 7) % 26) + 'a';
                } else {
                    c = ((c - 'A' - 7) % 26) + 'A';
                }
            }
        }
    }
        };
    public:
        TextCoder(string &str): text{str} {};
        TextCoder(const TextCoder &t): text{t.text} {};
        string get_ciphertext() {
            encoder();
            return text;
        }
        string get_deciphertext() {
            decoder();
            return text;
        }
};
View Code task5.cpp
#include "textcoder.hpp"
#include <iostream>
#include <string>

void test() {
    using namespace std;

    string text, encoded_text, decoded_text;

    cout << "输入英文文本: ";
    while (getline(cin, text)) {
        encoded_text = TextCoder(text).get_ciphertext();  // 这里使用的是临时无名对象
        cout << "加密后英文文本:\t" << encoded_text << endl;

        decoded_text = TextCoder(encoded_text).get_deciphertext(); // 这里使用的是临时无名对象
        cout << "解密后英文文本:\t" << decoded_text << endl;
        cout << "\n输入英文文本: ";
    }
}

int main() {
    test();
}
View Code 运行结果:

 

task6.cpp源码

task6.cpp:

#include<iostream>
#include<string>
#include<vector>
#include "info.hpp"

const int capacity = 100;


int main()
{
    vector<Info> audience_info_list;

    cout << "录入信息:" << endl;
    cout << endl;
    cout << "昵称     联系方式(邮箱/手机号)     所在城市     预定参加人数     " << endl;
    char choice;
    int sum=0;
    string nickname, contact, city;
    int n;
    while(cin >> nickname >> contact >> city >> n)
    {
        sum+=n;
        if(sum > capacity)
        {
            sum-=n;
            cout << "对不起,只剩" << capacity-sum << "个位置" << endl;
            cout << "1.输入u,更新(update)预定信息" << endl
                 << "2.输入q, 退出预定" << endl
                 <<"你的选择: ";
            cin >> choice;

            if(choice=='u')
            {
                cin >> nickname >> contact >> city >> n;
                Info a(nickname,contact,city,n);
                audience_info_list.push_back(a);
                sum+=n;
            }
            else
             break;
        }
        else audience_info_list.push_back(Info(nickname, contact, city, n));
    }
    cout << "截至目前,一共有" << sum << "位听众预定参加。预定听众信息如下:" << endl;
    for(auto &Info:audience_info_list)
    {
        Info.print();
    }
}
View Code

info.hpp:

#include <iostream>

using namespace std;

class Info {
private:
    string nickname;
    string contact;
    string city;
    int n;

public:
    Info(string nickname, string contact, string city, int n) : nickname{nickname}, contact{contact}, city{city}, n{n} {};
    print() {
        cout << "昵称: " << nickname << endl;
        cout << "联系方式:" << contact << endl;
        cout << "所在城市: " << city << endl;
        cout << "预定人数; " <<  n <<endl;
    }
};
View Code

运行结果:

 

 

标签:库类,std,string,C++,cpp,using,include,模板,cout
From: https://www.cnblogs.com/202283230013nuister/p/17868727.html

相关文章

  • 实验4 现代C++标准库与类模板
    实验任务5textcoder.hpp#programonce#include<iostream>#include<string>usingnamespacestd;classTextCoder{private:stringtext;voidencoder();voiddecoder();public:TextCoder(string&str);stringget_ciphertext(......
  • 实验4 现代C++标准库与类模板
    实验任务51#include<iostream>2#include<string>3usingnamespacestd;4classTextCoder5{6public:7TextCoder()=default;8TextCoder(stringstr);9stringget_ciphertext();10stringget_deciphertext();11......
  • Linux Mint(Ubuntu)系统VS Code C/C++环境配置include error问题
    1.问题描述安装完成LinuxMint后发现随系统自带了gcc,心里比较开心,以为自己不需要装了。但是在安装完VSCode之后,一直提示#includeerrorsdetected.PleaseupdateyourincludePath.Squigglesaredisabledforthistranslationunitlinux2.解决方案重新通过apt安装gcc......
  • 实验4 现代c++标准库与类模板
    实验任务1task1.cpp源码task1_1.cpp:1#include<iostream>23usingstd::cout;4usingstd::endl;56//类A的定义7classA{8public:9A(intx0,inty0):x{x0},y{y0}{}10voidshow()const{cout<<x<<","<......
  • 实验四 现代c++ 标准库与类的模板
    1.普通数组、array、vector的相关性,以及,区别相关性存储多个元素:1.普通数组:使用C风格数组声明和定义,大小固定。2.array:是C++11引入的标准库容器,提供了数组的替代,大小固定。3.vector:是C++标准库中的动态数组,大小可以动态调整。元素访问:1.普通数组和array:使用索......
  • C++ 泛型编程之可变参数包
    C++泛型编程之可变模板参数·variadictemplates可以表示0到任意个数、任意类型的参数1.可变模板参数的展开:template<typename...Args> //可以将参数包展开一个个独立的参数voidfunc(Args...args); //声明一个参数包Args...args这个参数包可以包括0到任意个模板参数......
  • C++20语言核心特性的变化
    usingforEnumerationValues  对比一下C++20前后的区别:enumclassState{open,progress,done=9};//BeforeC++20voidprint(States){switch(s){caseState::open:std::cout<<"open\n";brea......
  • 实验4 现代C++标准库与类模板
    实验任务5task5.cpp#include"Textcoder.hpp"#include<iostream>#include<string>voidtest(){ usingnamespacestd; stringtext,encoded_text,decoded_text; cout<<"输入英文文本:"; while(getline(cin,text)) { encoded_t......
  • 实验4 现代C++标准库与类模板
    四、实验内容1.实验任务1//在C++中定义和使用类模板task1_1.cpp#include<iostream>usingnamespacestd;//类A的定义classA{public:A(intx0,inty0):x{x0},y{y0}{}voidshow()const{cout<<x<<","<<y<<endl;}p......
  • 实验4 现代C++标准库与类模板
    实验任务1task1task1_1.cpp#include<iostream>usingstd::cout;usingstd::endl;classA{public:A(intx0,inty0):x{x0},y{y0}{}voidshow()const{cout<<x<<","<<y<<endl;}private:in......