输出数组

Description
写一个MyArray类来封装一个数组,实现下标访问这个功能。类的调用格式见append.cc
Input
输入分为两部分:第一部分是k个字符串和两个下标m、n;第二部分是k个整数和两个下标m、n。
Output
输出为两部分:输出从下标m到n的字符串和整数,分两行输出。

Sample Input
9
abc def ghi jkl mn opq rst uvw xyz
2 7
4
123 234 345 567
0 1
Sample Output
ghi jkl mn opq rst uvw
123 234
HINT
Append Code
append.cc,

int main()
{
    int k, m, n;
 
    cin >> k;
    MyArray<string> s(k);
    for(int i = 0; i < k; i++)
        cin >> s[i];
 
    cin >> m >> n;
    cout << s[m];
    for(int i = m + 1; i <= n; i++)
        cout << " " << s[i];
    cout << endl;
 
    cin >> k;
    MyArray<int> a(k);
    for(int i = 0; i < k; i++)
        cin >> a[i];
 
    cin >> m >> n;
    cout << a[m];
    for(int i = m + 1; i <= n; i++)
        cout << " " << a[i];
    cout << endl;
}

AC代码一

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class MyArray
{
private:
    T *a;
    int length;
public:
    MyArray(int l=0):length(l)
    {
        a=new T[length];
    }
    T& operator[](int n)
    {
        return a[n];
    }
};
int main()
{
    int k, m, n;

    cin >> k;
    MyArray<string> s(k);
    for(int i = 0; i < k; i++)
        cin >> s[i];

    cin >> m >> n;
    cout << s[m];
    for(int i = m + 1; i <= n; i++)
        cout << " " << s[i];
    cout << endl;

    cin >> k;
    MyArray<int> a(k);
    for(int i = 0; i < k; i++)
        cin >> a[i];

    cin >> m >> n;
    cout << a[m];
    for(int i = m + 1; i <= n; i++)
        cout << " " << a[i];
    cout << endl;
}

AC代码二

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
template<typename T>
class MyArray
{
private:
    vector<T> a;
public:
    MyArray(int l)
    {
        a.resize(l);
    }
    T& operator[](int i)
    {
        return a[i];
    }
};
int main()
{
    int k, m, n;

    cin >> k;
    MyArray<string> s(k);
    for(int i = 0; i < k; i++)
        cin >> s[i];

    cin >> m >> n;
    cout << s[m];
    for(int i = m + 1; i <= n; i++)
        cout << " " << s[i];
    cout << endl;

    cin >> k;
    MyArray<int> a(k);
    for(int i = 0; i < k; i++)
        cin >> a[i];

    cin >> m >> n;
    cout << a[m];
    for(int i = m + 1; i <= n; i++)
        cout << " " << a[i];
    cout << endl;
}

注意:
1、main函数中的MyArray<string> s(k);k代表的长度;
2、如果对象是char* 或者int* 等,在private中就必须要带length,但是,vector等容器中自带length,不需要带着length;
3、strlen最好不要放在循环里,因为它的执行时间很长,最好把它赋给一个数len,用len代替它

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值