когда я пытаюсь скомпилировать его, у меня появляется эта ошибка, и я действительно не знаю, что делать.
Может быть, вы можете помочь мне об этом.
main.cpp:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <list>
using namespace std;
list<int> liste;
int size=0;
void list_initialization(){
cout << "Quicksort" << endl << endl;
cout <<"List Initialization" << endl;
while ((size<1)||size>100){
cout << "Please enter the size (between 1 and 100)" << endl;
cin >> size;
}
srand ( time(NULL) );
for (int i=0; i<size; i++){
liste.push_back(rand() %100 +1);
}
}
void list_display(){
cout << endl;
for (list<int>::const_iterator ite=liste.begin(), end=liste.end(); ite!=end; ++ite)
cout << *ite << " ";
cout << endl;
}
int choose_pivot( int const& left, int const& right){
int pivot;
pivot = rand()%(right-left) + left ;
return pivot;
}
int partition(int left, int right, int pivotIndex){//We Save pivotValue
list<int>::iterator itPivotIndex = liste.begin();
advance (itPivotIndex, pivotIndex);
int pivotValue = *itPivotIndex;
//Those 2 iterators will be used to swap 2 elements
list<int>::iterator itSwap1 = liste.begin();
list<int>::iterator itSwap2 = liste.begin();
//2 iterators to point left and right elements
list<int>::iterator itLeft = liste.begin();
advance (itLeft, left);
list<int>::iterator itRight = liste.begin();
advance (itRight, right);
//1 iterator to point the StoreIndex
list<int>::iterator itStoreIndex=itLeft;//Move Pivot to End
advance(itSwap1, pivotIndex);
advance(itSwap2, right);
swap(*itSwap1, *itSwap2);//Move all elements less than pivotValue before the pivot
for(list<int>::iterator it=itLeft; it!=itRight; it++)
if (*it < pivotValue){
//Swap array[k] and array[storeIndex]
itSwap1=it;
itSwap2=itStoreIndex;
swap(*itSwap1, *itSwap2);
itStoreIndex++;
}
//Move pivot to its final place
swap(*itStoreIndex, *itRight);
return (distance(liste.begin(), itStoreIndex));
}void quicksort (int left, int right){
int pivotNewIndex=0;
list<int>::iterator ite=liste.begin();
if (left < right){
int pivotIndex = choose_pivot(left,right);
advance (ite,pivotIndex);
cout << "The pivot is " << *ite <<endl;
pivotNewIndex = partition(left, right, pivotIndex);
list_display();
cout << endl;
// Recursively sort elements smaller than the pivot
quicksort(left, pivotNewIndex - 1);
// Recursively sort elements at least as big as the pivot
quicksort(pivotNewIndex + 1, right);
}
}
int main()
{
list_initialization();
list_display();
cout << endl;
int left=0;
int right=size-1;
quicksort(left, right);
cout << "Sorted List :";
list_display();
cout << endl;
return 0;
}
quicksort.cpp:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <list>
using namespace std;
extern int array [];
int selectPivot( int const& left, int const& right);
int Partition(int left, int right, int pivotIndex);
void sorting (int left, int right);
int selectPivot( int const& left, int const& right){
int pivot;
pivot = rand()%(right-left) + left ;
return pivot;
}
int Partition(int left, int right, int pivotIndex){
int temp=0;
int storeIndex=left;
int pivotValue = array[pivotIndex];temp=pivotValue;
pivotValue=array[right];
array[right]=temp;for (int k=left; k<right; k++)
if (array[k] < pivotValue){
temp=array[k];
array[k]=array[storeIndex];
array[storeIndex]=temp;
storeIndex++;
}
temp = array[storeIndex];
array[storeIndex]=array[right];
array[right]=temp;
return storeIndex;
}void sorting (int left, int right){
int pivotNewIndex=0;
if (left < right){
int pivotIndex = selectPivot(left,right);
pivotNewIndex = Partition(left, right, pivotIndex);sorting(left, pivotNewIndex - 1);sorting(pivotNewIndex + 1, right);
}
}
————— 1> —— Начата сборка: Проект: практический2, Конфигурация: Отладка Win32 —— 1> Компиляция … 1> quicksort.cpp 1> Связывание … 1> quicksort.obj: ошибка LNK2001 : неразрешенный внешний символ «int * array» (? array @@ 3PAHA) 1> C: \ Users \ Amed \ Documents \ Visual Studio 2008 \ Projects \ практический2 \ Debug \ Pract2.exe: фатальная ошибка LNK1120: 1 неразрешенный внешний 1> Журнал сборки был сохранен в «file: // c: \ Users \ Amed \ Documents \ Visual Studio 2008 \ Projects \ Practical2 \ Practical2 \ Debug \ BuildLog.htm» 1> практическая 2 — 2 ошибки, 0 предупреждений
========== Построение: 0 выполнено, 1 не выполнено, 0 обновлено, 0 пропущено ===========
Вы написали extern int array[]
в quicksort.cpp
, но на самом деле не определил это нигде. Есть неразрешенный символ, потому что он нигде не существует, поэтому компоновщик не может найти его для его разрешения.
Вы могли бы исправить нерешенное внешний изменив его на:
массив int [1024];
Заметки:
1024 был выбран произвольно в качестве размера массива. Выбор размера (ов) статически определенного массива в стиле C иногда бывает непростым делом.
Вы можете избежать этой проблемы, переключившись на динамическую структуру, такую как класс std :: vector стандартной библиотеки:
std :: vector nameOtherThanArray; //;)
Называть (глобальную) переменную «массив», вероятно, слишком генетически, чтобы придать ожидаемое использование в дополнение к возможному конфликту с именами в других библиотеках. Я не пытался пересмотреть остальную часть кода, но если бы я писал настоящий метод общего назначения, я хотел бы передать структуру, которой манипулируют, или, если это просто временный помощник, объявить его локально. Конечно, как я сказал, я не внимательно изучил остальную часть кода, поэтому ваш путь может иметь смысл по другой причине.