实验1 类和对象

// 标准库string, vector, array基础用法

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

// 函数模板
// 对满足特定条件的序列类型T对象,使用范围for输出
template<typename T>
void output1(const T &obj) {
    for(auto i: obj)
        std::cout << i << ", ";
    std::cout << "\b\b \n";
}

// 函数模板
// 对满足特定条件的序列类型T对象,使用迭代器输出
template<typename T>
void output2(const T &obj) {
    for(auto p = obj.begin(); p != obj.end(); ++p)
        std::cout << *p << ", ";
    std::cout << "\b\b \n";
}

// array模板类基础用法
void test_array() {
    using namespace std;

    array<int, 5> x1;   // 创建一个array对象,包含5个int元素,未初始化
    cout << "x1.size() = " << x1.size() << endl;  // 输出元素个数
    x1.fill(42);        // 把x1的所有元素都用42填充
    x1.at(0) = 999;     // 把下标为0的元素值修改为999
    x1[4] = -999;       // 把下表为4的元素值修改为-999
    cout << "x1: ";
    output1(x1);        // 调用模板函数output1输出x1
    cout << "x1: ";
    output2(x1);        // 调用模板函数output1输出x1

    array<int, 5> x2{x1};
    cout << boolalpha << (x1 == x2) << endl;
    x2.fill(22);
    cout << "x2: ";
    output1(x2);

    swap(x1, x2);   // 交换array对象x1, x2
    cout << "x1: ";
    output1(x1);
    cout << "x2: ";
    output1(x2);
}

// vector模板类基础用法
void test_vector() {
    using namespace std;

    vector<int> v1;
    cout << v1.size() << endl;      // 输出目前元素个数
    cout << v1.max_size() << endl;  // 输出元素个数之最大可能个数
    v1.push_back(55);               // 在v1末尾插入元素
    cout << "v1: ";
    output1(v1);

    vector<int> v2 {1, 0, 5, 2};
    v2.pop_back();                  // 从v2末尾弹出一个元素
    v2.erase(v2.begin());         // 删除v2.begin()位置的数据项
    v2.insert(v2.begin(), 999);     // 在v1.begin()之前的位置插入
    v2.insert(v2.end(), -999);      // 在v1.end()之前的位置插入
    cout << v2.size() << endl;
    cout << "v2: ";
    output2(v2);

    vector<int> v3(5, 42);         //创建vector对象,包含5个元素,每个元素值都是42
    cout << "v3: ";
    output1(v3);

    vector<int> v4(v3.begin(), v3.end()-2); // 创建vector对象,以v3对象的[v3.begin(), v3.end()-2)区间作为元素值
    cout << "v4: ";
    output1(v4);
}

// string类基础用法
void test_string() {
    using namespace std;

    string s1{"oop"};
    cout << s1.size() << endl;
    for(auto &i: s1)
        i -= 32;
    s1 += "2023";
    s1.append(", hello");
    cout << s1 << endl;
}

int main() {
    using namespace std;

    cout << "===========测试1: array模板类基础用法===========" << endl;
    test_array();

    cout << "\n===========测试2: vector模板类基础用法===========" << endl;
    test_vector();

    cout << "\n===========测试3: string类基础用法===========" << endl;
    test_string();
}

 

posted @ 2023-10-13 11:13  49809266  阅读(36)  评论(0)    收藏  举报