首页 > 编程语言 >实验3 数组、指针与现代C++标准库

实验3 数组、指针与现代C++标准库

时间:2022-10-19 17:50:42浏览次数:54  
标签:std string int void C++ 数组 include 指针 cout

实验目的

  1. 知道什么是类模板,会正确定义和使用简单的类模板
  2. 能够描述数组的特性,会使用C++语法正确定义和访问内置数组,知道其局限性
  3. 能够解释指针变量的特性,会使用C++语法正确定义指针变量间接访问对象
  4. 能熟练使用现代C++标准库中的数组模板类array、动态数组类模板vector、字符串类string
  5. 知道现代C++标准库中迭代器,会使用迭代器访问各种序列容器对象
  6. 针对具体问题场景,能够灵活、组合使用C++标准库与自定义类对问题进行抽象和编程求解

实验内容

5.实验任务5

实验代码

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

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

public:
    Info(string, string, string, int);
    void print();
};
Info::Info(string Name = {}, string Contact = {}, string City = {}, int n = 0) : nickname{Name}, contact{Contact}, city{City},number{n}{}
void Info::print()
{
    cout << setfill(' ') << setw(16) << left << "昵称:" << nickname << endl
         << setfill(' ') << setw(16) << left << "联系方式:" << contact << endl
         << setfill(' ') << setw(16) << left << "所在城市:" << city << endl
         << setfill(' ') << setw(16) << left << "预定人数:" << number << endl
         << endl;
}
int Number=0;
int main(int argc, char const *argv[])
{
    const int capacity = 100;
    vector<Info> audience_info_list;
    int n;
    string s, s1, s2, s3;
    cout << "录入信息:" << endl
         << endl
         << setfill(' ') << setw(16) << left << "昵称"
         << setfill(' ') << setw(28) << left << "联系方式(邮箱/手机号)"
         << setfill(' ') << setw(16) << left << "所在城市"
         << setfill(' ') << setw(16) << left << "预定参加人数" << endl;
    while (cin >> s1)
    {
        cin >> s2 >> s3 >> n;
        audience_info_list.push_back(Info(s1, s2, s3, n));
        Number+=n;
        if (Number > capacity)
        {
            Number-=n;
            cout << "对不起,只剩" << capacity - Number << "个位置。" << endl
                 << "1.输入u,更新(update)预定信息" << endl
                 << "2.输入q,退出预定" << endl
                 << "你的选择:";
            cin >> s;
            if (s == "q")
            {
                break;
            }
            if (s == "u")
            {
                audience_info_list.pop_back();
                continue;
            }
        }
    }
    cout <<endl<< "截止目前,一共有" << Number << "位听众预定参加。预定听众信息如下:" << endl;
    for (auto &item : audience_info_list)
    {
        item.print();
    }
    return 0;
}

测试结果

test5.1
test5.2
test5.3

6.实验任务6

实验代码

textcoder.hpp

#pragma once

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

class TextCoder
{
private:
    string text;

public:
    TextCoder(string);
    string get_ciphertext();
    string get_deciphertext();

private:
    void encoder(string &s)
    {
        for (auto &i : s)
        {
            if (isalpha(i))
            {
                i += 5;
                if (i > 'z'||i<'a'&&i>'Z')
                i -= 26;
            }
        }
    }
    void decoder(string &s)
    {
        for (auto &i : s)
        {
            if (isalpha(i))
            {
                i -= 5;
                if (i < 'A'||i>'Z'&&i<'a')
                i += 26;
            }
        }
    }
};

TextCoder::TextCoder(string Text) : text{Text}
{
}

string TextCoder::get_ciphertext()
{
    encoder(text);
    return text;
}

string TextCoder::get_deciphertext()
{
    decoder(text);
    return text;
}

task6.cpp

#pragma once

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

class TextCoder
{
private:
    string text;

public:
    TextCoder(string);
    string get_ciphertext();
    string get_deciphertext();

private:
    void encoder(string &s)
    {
        for (auto &i : s)
        {
            if (isalpha(i))
            {
                i += 5;
                if (i > 'z'&&i>'Z')
                i -= 26;
            }
        }
    }
    void decoder(string &s)
    {
        for (auto &i : s)
        {
            if (isalpha(i))
            {
                i -= 5;
                if (i > 'z'&&i>'Z')
                i += 26;
            }
        }
    }
};

TextCoder::TextCoder(string Text) : text{Text}
{
}

string TextCoder::get_ciphertext()
{
    encoder(text);
    return text;
}

string TextCoder::get_deciphertext()
{
    decoder(text);
    return text;
}

测试结果

test6

1.实验任务1

实验代码

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;
};

int main() {
    A a(3, 4);
    a.show();

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

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;
};

int main() {
    X<int> x1(3, 4);
    x1.show();

    X<double> x2(3.2, 5.6);
    x2.show();

    X<std::string> x3("hello", "c plus plus");
    x3.show();
}

测试结果

test1.1
test1.2

2.实验任务2

实验代码

task2_1.cpp

#include <iostream>
#include <string>

int main() {
    using namespace std;

    string s1, s2;
    s1 = "nuist";                                 // 赋值
    s1[0] = 'N';                                  // 支持通过[]和索引方式访问
    s1.at(1) = 'U';                               // 支持通过xx.at()方法访问
    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("@"); // 查找子串"@"第一次出现的索引位置,如果失败,返回string::npos
    if (pos == string::npos)
        cout << "illegal email address";
    else {
        auto s1 = email.substr(0, pos);  // 取子串, 从索引0 ~ pos-1
        auto s2 = email.substr(pos + 1); // 取子串,从pos+1到末尾
        cout << s1 << endl;
        cout << s2 << endl;
    }

    string phone{"15216982937"};
    cout << phone.replace(3, 5, string(5, '*')) << endl; // 把从索引位置为3开始的连续5个字符替换成*

    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(); // 方法c_str()把string类字符串组转换成C风格的字符串
    cout << pstr << endl;

    string s6{"12306"};
    int x1 = stoi(s6); // 把string转换成int
    cout << x1 << endl;

    int x2 = 12306;
    string s7 = to_string(x2);  // 把int转换成string
    cout << s7 << endl;

    double x3 = 123.06;
    string s8 = to_string(x3); // 把double转换成string
    cout << s8 << endl;
}

task2_2.cpp

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

int main() {
    using namespace std;

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

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

    string s2, s3;
    cout << prompt;
    getline(cin, s2, ' ');  // 从输入流中提取字符串给s2,直到指定分隔符空格
    getline(cin, s3);
    cout << "s2: " << s2 << endl;
    cout << "s3: " << s3 << endl;
}

task2_3.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";
    }
}

task2_4.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;
}

测试结果

test2.1
test2.2
test2.3
test2.4

3.实验任务3

实验代码

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对象v1, 未指定大小, 元素是int型, 未初始化
    vector<int> v2(5);             // 创建一个vector对象v2, 包含5个元素,元素是int型,初始值是默认值0
    vector<int> v3(5, 42);         // 创建一个vector对象v3, 包含5个元素,元素是int型,指定初始值是42
    vector<int> v4{1, 9, 8, 4}; // 创建一个vector对象v4, 元素是int型,使用初始化列表方式
    vector<int> v5{v4};            // 创建一个vector对象v5, 使用已经存在的对象v4创建

    output(v2);
    output(v3);
    output(v4);
    output(v5);
    return 0;
}

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);
    return 0;
}

测试结果

test3.1
test3.2

4.实验任务4

实验代码

#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, 2, 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 << "test1: " << endl;
    test1();

    cout << "test2: " << endl;
    test2();

    cout << "test3: " << endl;
    test3();
    return 0;
}

测试结果

test4

标签:std,string,int,void,C++,数组,include,指针,cout
From: https://www.cnblogs.com/PhantomGmc/p/16803792.html

相关文章

  • 实验3 数组,指针与现代c++标准库
    实验五:Info.hpp1#include<iostream>2#include<string>3#include<iomanip>4usingnamespacestd;5classInfo6{7private:8......
  • 找到数组中第k小的元素
    intpartition(inta[],intstart,intend){//快排的partition操作if(start>=end){returnstart;}inti=start,j=end;inttmp=......
  • go 数组去重
    //rmDuplicate数组去重funcrmDuplicate(list[]string)[]string{varx[]stringfor_,i:=rangelist{iflen(x)==0{x=ap......
  • RestTemplate请求参数有MultipartFile[] 附件数组
    一、RestTemplate请求参数有MultiplateFile[]附件数组的情况,该如何处理二、代码示例@PostMapping("/testSendEmail")@ResponseBodypublicbooleantestSendEma......
  • C++11 实现一个自动注册的工厂
    之前在项目代码里面看到同事写了个自动注册的工厂类,虽然当时我看不懂,但我大受震撼。今天又重新温习了一下这种写法,分享给大家,可见学好C++是多么的重要。实现动机工厂方法......
  • React:数组、列表渲染
    数组JSX允许在模板中插入数组,数组会自动展开所有成员vararr=[<h1>HTML</h1>,<h2>CSS</h2>];ReactDOM.render(<div>{arr}</div>,document.getElementB......
  • JavaScript数组常用数组函数
    constarr=[1,12,13,4,5,6,7,8];//找出符合条件的第一个元素,并返回。否返回undefinedconstfount=arr.find((x)=>{returntypeof(x)==="number";})consol......
  • C++类模型漫谈(二)
    系统基于32位,MSVC编译器,VS开发工具1、通过对象对成员函数的调用,默认会给参数传进去一个this指针,该指针为对象的首地址,这个过程通常被编译器隐藏起来了。对象直接调用成员......
  • Demo38_java数组05_前半段
    //数组与for循环的基本操作运行packagecom.HuanXin.array_6;publicclassDemo03{publicstaticvoidmain(String[]args){int[]A={1,2,3,4,5};......
  • c++中正确编写包含类的头文件
         ......