为什么我没有为我的c ++代码获得正确的输出?

时间:2016-01-28 06:28:53

标签: c++ arrays exception-handling output

所以我写的c ++代码基本上是一个数组并在数组中插入值,同时向右移动以产生空间,如果数组已满,那么它会生成一个新的数组,用于复制旧的数值。第一个阵列进入第二个。这是执行该操作的代码:

#include <iostream>

#include "dynamic_array.h"

using namespace std;

dynamic_array::dynamic_array() {
    size = 0;
    allocated_size = 0;
    try {
        array = new int [size + BLOCK_SIZE];    
    } catch (bad_alloc){
        throw exception (MEMORY_EXCEPTION);
    }
}

dynamic_array::~dynamic_array() {
    delete []array;
}

int dynamic_array::get_size(void) const {
    return size;
}

int dynamic_array::get_allocated_size(void) const {
    return allocated_size;
}

int& dynamic_array::operator[](unsigned int i) {
    if (i >= (unsigned)get_size()){
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    }
    return array[i];
}

const int& dynamic_array::operator[](unsigned int i) const {
    if (i < 0 || i > (unsigned)get_size()){
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    }
    return array[i];
}

void dynamic_array::insert(int x, int i) {
    if (get_size() == get_allocated_size()){
        int *new_array = new int[get_allocated_size() + BLOCK_SIZE]; 
        allocated_size = allocated_size + BLOCK_SIZE;
        for (int i = 0; i < get_size(); i++){
            new_array[i] = array[i];
        }
        delete []array;
        array = new_array;
    }
    try {
        shift_right(i, get_size() - 1, 1);
        array[i] = x;
        size = size + 1;
    } catch (bad_alloc){
        throw exception (MEMORY_EXCEPTION);
    }
    if (i < 0 or i > get_size()){
        throw exception(SUBSCRIPT_RANGE_EXCEPTION);
    }
    return;
}

void dynamic_array::shift_right(int start, int end, int delta){
    try{
        for(int i=start; i<end; i++){
            array[i+delta] = array[i];
        }
    } catch (bad_alloc){
        throw exception (MEMORY_EXCEPTION);
    }
    return;
}

变量被声明为构造函数类

    BLOCK_SIZE = 5,
    SUBSCRIPT_RANGE_EXCEPTION = 1,
    MEMORY_EXCEPTION = 2,
int *array; // pointer to dynamically allocated memory
int allocated_size; // total number of elements in allocated memory
int size; // number of active elements

为了测试代码,我使用了这个:

#include <iostream>
#include <stdlib.h>

#include "dynamic_array.h"

using namespace std;

int test_const_operator(const dynamic_array &a, int i) {
    return a[i];
}

void print_array(dynamic_array &a) {
    cout << "size: " << a.get_size() << endl;
    cout << "allocated size: " << a.get_allocated_size() << endl;
    for (int i = 0; i < a.get_size(); i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

int main() {
    dynamic_array a;

    cout << "***** array size: 0" << endl;
    print_array(a);

    cout << "check for exception in empty array" << endl;
    try {
        a[0];
    } catch (dynamic_array::exception x) {
        cout << "caught: " << x.n << endl;
    }
    try {
        test_const_operator(a, 0);
    } catch (dynamic_array::exception x) {
        cout << "caught const: " << x.n << endl;
    }

    cout << "***** array size: 1" << endl;
    a.insert(2,0);
    cout << test_const_operator(a, 0) << endl;
    print_array(a);

    cout << "***** array size: 2" << endl;
    a.insert(4,1);
    print_array(a);

    cout << "***** array size: 3" << endl;
    a.insert(3,1);
    print_array(a);

    cout << "***** trigger subscript range exception" << endl;
    try {
        a.insert(5,4);
    } catch (dynamic_array::exception x) {
        cout << "caught: " << x.n << endl;
    }

    cout << "***** trigger re-allocation" << endl;
    a.insert(1,0);
    a.insert(5,4);
    a.insert(99,2);
    print_array(a);
}

现在我运行此代码时获得的输出是:

***** 
array size: 0

size: 0

allocated size: 0


check for exception in empty array

caught: 1

***** 
array size: 1
2

size: 1

allocated size: 5
2 

***** 
array size: 2

size: 2

allocated size: 5
2 4 

***** 
array size: 3

size: 3

allocated size: 5
2 3 0 

***** 
trigger subscript range exception

***** 
trigger re-allocation
size: 7
allocated size: 10
1 2 99 2 2 2 1 

但那不是我想要的输出。这是我应该得到的东西:

caught: 1

caught const: 1

第7行没有捕获常量。在第18行,它应该说allocated size: 52 3 4,而是说allocated size: 52 3 0。在它说trigger subscript range exception之后它应该在它下面说caught: 1但是对我来说它没有说什么。最后在第二行到最后一行它应该说大小:6而不是大小:7。最后一行应该说allocated size: 101 2 99 3 4 5。所以我在获得正确的输出方面非常接近但我仍然对这些最后几位有点困惑以及如何获得正确的输出。要运行代码,我还使用如下所示的.h文件:

using namespace std;

class dynamic_array {
public:
    enum {
        BLOCK_SIZE = 5,
        SUBSCRIPT_RANGE_EXCEPTION = 1,
        MEMORY_EXCEPTION = 2,
    };

    /*Purpose
    *   create an array with size 0
    * Preconditions
    *   none
    * Exceptions
    *   if there is not enough dynamic memory available
    *       throw exception(MEMORY_EXCEPTION)
    */
    dynamic_array();

    /*Purpose
    *   create an array containing a copy of the elements in a
    * Preconditions
    *   none
    * Exceptions
    *   if there is not enough dynamic memory available
    *       throw exception(MEMORY_EXCEPTION)
    */

    int get_size(void) const;

    /*Purpose
    *   return the allocated size of the array
    * Preconditions
    *   none
    * Exceptions
    *   none
    */
    int get_allocated_size() const;

    /*Purpose
    *   return a reference to the element with index i
    * Preconditions
    *   none
    * Exceptions
    *   if i >= get_size()
    *       throw exception(SUBSCRIPT_RANGE_EXCEPTION)
    */
    int& operator[](unsigned int i);
    /*Purpose
    *   return a reference to the element with index i
    * Preconditions
    *   none
    * Exceptions
    *   if i >= get_size()
    *       throw exception(SUBSCRIPT_RANGE_EXCEPTION)
    */
    const int& operator[](unsigned int i) const;

    /*Purpose
    *   insert x at postion i
    *   shift elements at positions i and higher one position to the right
    * Preconditions
    *   none
    * Exceptions
    *   if i < 0 or i > get_size()
    *       throw exception(SUBSCRIPT_RANGE_EXCEPTION)
    *   if there is not enough dynamic memory available
    *       throw exception(MEMORY_EXCEPTION)
    */
    void insert(int x, int i);

    /*Purpose
    *   insert the elements of a at postion i
    *   shift elements at positions i and higher n positions to the right
    *       where n is the size of a
    * Preconditions
    *   none
    * Exceptions
    *   if i < 0 or i > get_size()
    *       throw exception(SUBSCRIPT_RANGE_EXCEPTION)
    *   if there is not enough dynamic memory available
    *       throw exception(MEMORY_EXCEPTION)
    */

    class exception {
        public:
            exception(int n0) { n = n0; };
            int n;
    };
private:
    /*purpose
    *   shift array[start..end-1] delta positions to the left
    * preconditions
    *   0 <= start <= end <= size
    *   array[start-delta..end-delta-1] legally addressable
    * examples
    *   given array with contents {0,2,4,6,8, 10,12,14,16,18}:
    *       shift(2,4,2)
    *           changes the contents to {4,6,4,6,8, 10,12,14,16,18}
    *       shift(2,2,1)
    *           leaves array unchanged
    */
    void shift_right(int start, int end, int delta);

    int *array; // pointer to dynamically allocated memory
    int allocated_size; // total number of elements in allocated memory
    int size; // number of active elements
};

1 个答案:

答案 0 :(得分:1)

您没有收到i输出,因为if (i < 0 || i > (unsigned)get_size()){ throw exception(SUBSCRIPT_RANGE_EXCEPTION); } 没有抛出异常。

i == 0设置为0的情况下调用该函数,抛出异常的测试是:

size == 0

array时不是这样。

您甚至没有遇到未定义的行为,因为当BLOCK_SIZE = 5 array[0]成员实际上指向包含5个元素的分配时(因为import time from twisted.internet import reactor, threads def functionOne(x): print x def functionTwo(x): time.sleep(10) print x commands = [(functionOne, ["First Function"], {})] commands.append((functionTwo, ["Second Function"], {})) reactor.listenUDP(9999, threads.callMultipleInThread(commands)) reactor.run() )所以实际上存在{{1}} } element。