2015-01-27 4 views
1

이것은 가능한 한 많은 소수를 찾는 것을 목표로하는 비 등급 도전 과제를위한 것입니다. 제약 조건 중 하나는 new/delete를 사용해야한다는 것입니다. 따라서 std::vector은 옵션이 아닙니다. 이 문제에서는 배열에 동적으로 생성 된 array라는 배열을 추가해야합니다.이 배열은 소수를 포함합니다. 내 목표는 벡터와 비슷한 기능을 수행하는 것입니다. 새 메모리는 현재 배열에 충분한 공간이없는 경우에만 할당해야하며 현재 배열은 길이가 할당 된 2 배의 새 배열을 채울 때 사용됩니다. 목록에 전성기를 추가하는 내 기능동적 배열을 더 크게 만듭니다.

void PrimeList::addPrimeToList(int newPrime) { 
    if(sizeof(list)/sizeof(int) > total) { // there is still room in the array 
     list[total++] = newPrime; 
    } else { // list has run out of space to put values into 
     int *newList = new int [total*2]; // new list to hold all previous primes and new prime 
     for(int i=0; i < total; i++) { // for every old prime 
      newList[i] = list[i]; // add that old prime to the new list 
     } 
     newList[total++] = newPrime; // set largest and the last index of the new list to the new prime 
     delete [] list; // get rid of the old list 
     list = newList; // point the private data member list to the newly created list. 
    } 
} 

주 이하 : 총이 시점까지 발견 소수의 양을 보유 개인 데이터 멤버입니다.

내 문제는 첫 번째 두 호출이 항상 if의 첫 번째 부분을 실행한다는 점을 제외하면 else 문과 함수가 호출 될 때마다 시간이 많이 걸리는 할당/할당 취소가 발생한다는 것입니다. 나는 if 부분이 대다수의 시간을 실행할 것이라고 생각할 것입니다 - 목록에 여전히 공간이있을 때마다 - 그렇다면 왜 그렇게되지 않을까요? 이런

답변

1

이유는 어레이의 크기에 사용하는 식, 즉

sizeof(list)/sizeof(int) 

일정한 표현이다. 이 값은 list 포인터가 가리키는 할당 된 배열에 종속되지 않습니다.

if(allocatedSize > total) { // there is still room in the array 
    list[total++] = newPrime; 
} else { // list has run out of space to put values into 
    int *newList = new int [total*2]; // new list to hold all previous primes and new prime 
    allocatedSize *= 2; 
    for(int i=0; i < total; i++) { // for every old prime 
     newList[i] = list[i]; // add that old prime to the new list 
    } 
    newList[total++] = newPrime; // set largest and the last index of the new list to the new prime 
    delete [] list; // get rid of the old list 
    list = newList; // point the private data member list to the newly created list. 
} 
:

는이 코드가 작동을 별도로 할당 된 크기를 저장해야

관련 문제