Dotcpp  /  试卷列表  /  C++  /  题目 7756

请使用“答题”菜单或使用VC6打开考生文件夹proj3

请使用“答题”菜单或使用VC6打开考生文件夹proj3下的工程文件proj3,其中包含了类Integers和主函数main的定义。一个Integers对象就是一个整数的集合,其中包含0个或多个可重复的整数。成员函数 add将一个元素添加到集合中,成员函数remove从集合中删除指定的元素(如果集合中存在该元素),成员函数 filter去除集合中的所有负整数。请编写这个filter函数。此程序的正确输出结果应为:

5 28 2 -4 5 3 2 -75 27 66 31

5 28 2 -4 5 3 2 -75 27 66 31 6

5 28 2 -4 5 3 2 -75 27 66 31 6 -19

5 28 2 -4 5 3 -75 27 66 31 6 -19 4

5 28 2 -4 5 3 -75 27 66 31 6 -19 4

5 28 2 5 3 27 66 31 6 4

要求: 

补充编制的内容写在//********333********与//********666******** 两行之间。不得修改程序的其他部分。 

注意:相关文件包括:main.cpp、Integers.h。 

程序最后已经调用WriteToFile函数,使用另一组不同的测试数据, 将不同的运行结果输出到文件out.dat中。输出函数writeToFile已经编译 为obj文件。 

部分源程序如下:

/**********code.c**********/
# include "Integers.h"
# include <iomanip>
Integers::Integers(int data[], int size): counter(0){
    for(int i=0; i<size; i++) add(data[i]);
}
void Integers::add(int element){
    if(counter<MAXELEMENTS) elemK[counter++] = element;
}
void Integers::remove(int element){
    int j;
    for(j = counter - 1; j >= 0; j --)
        if(elem[j] == element) break;
    for(int i = j; i<counter - 1; i++) elem[i] = elem[i+1];
    counter -- ;
}
void Integers::filter(){
    //**********333**********
    //**********666**********
}
void Integers::show() const{
    for(int i = 0; i<getCount(); i++)
        cout<<setw(4)<<getElement(i);
    cout<<endl;
}
int main(){
    int d[] = {5,28,2,-4,5,3,2,-75,27,66,31};
    Integers s(d,11); s.show();
    s.add(6);
    s.show();
    s.add(-19);
    s.show();
    s.remove(2);
    s.show();
    s.add(4);
    s.show();
    s.filter();
    s.show();
    writeToFile("k:\k01\61010001\");
    return 0;
}
/**********code.c**********/

结果文件out.dat内容如下:

0,27,-2,9,67,62 ,

答案

for(int i=0; i

{

    If(getElement(i)<0)

    {

        for(int j=i; j<=getCount(); ++j)

        {

            elem[j]=elem[j+1];

        }

        --counter; }

    }

}


解析

补充的内容是如果该元素的值小于零,则不添加到集合 中,如果该元素的值大于0,则添加到集合中,添加元素的同时,集合 里的元素数量增加1。

题目信息

题号:7756
题型:简答题
知识点:C++
难度:普通