Permalänk
Medlem

Sortering av Arrayer

Hej sitter här med en array i c++ som jag ska sortera med hjälp av en funktion jag har skapat och får segmenterings fel(yay), problemet sitter någonstans i min funktion och jag vet inte riktigt vad som är fel....

Skulle uppskatta lite hjälp

Här är min kod:

Main.cpp :

#include <cstdlib> #include <iostream> #include "IntArray.h" using namespace std; int main(){ int n=100; IntArray ia(n);//=IntArray(n); //IntArray *ia=new IntArray(n); <-- ger segmenterings fel!! for(int i=0; i<n;i++){ ia[i]=rand()%10000; cout<<ia[i]<<endl; } ia.SelectionSort(ia, n); cin.get(); return 0; }

IntArray.h:

#ifndef INTARRAY_H #define INTARRAY_H class IntArray { public: IntArray(size_t size); IntArray(size_t size, int init_value); IntArray(const IntArray& orig); // Copy constructor ~IntArray(); void SelectionSort(IntArray, int); int operator[](int i) const; int& operator[](int i); private: IntArray(); int* begin; size_t size; }; #endif // INTARRAY_H_INCLUDED

IntArray.cpp:

#include<cstdlib> #include<iostream> #include "IntArray.h" using namespace std; IntArray::IntArray() { } IntArray::IntArray(size_t size):size(size), begin(new int[size]){ } IntArray::IntArray(size_t size, int init_value):size(size), begin(new int[size]){ for(size_t i = 0; i < size; i++){ begin[i]=init_value; } } IntArray::IntArray(const IntArray& orig) { } IntArray::~IntArray() { } int IntArray::operator [](int i) const{ return begin[i]; } int& IntArray::operator [](int i){ return begin[i]; } void IntArray::SelectionSort(IntArray ia, int size){ int i,j,tmp,iMin; int n=size; for (j = 0; j < n-1; j++) { iMin = j; for ( i = j+1; i < n; i++) { if (ia[i] < ia[iMin]) { iMin = i; } } if ( iMin != j ) { tmp=ia[j]; ia[j]=ia[iMin];//Här får jag mitt segmenterings fel enligt codeblocks... ia[iMin]=tmp; } } cout<<"sorterad -------------" << endl; for(int i=0; i<n;i++){ cout<<ia[i]<<endl; } }

Tack på förhand!

//Robbanj

Permalänk
Hedersmedlem
Skrivet av robbanj:

void IntArray::SelectionSort(IntArray ia, int size)

Vill du inte ha

IntArray& ia

här istället?

Permalänk
Medlem
Skrivet av Elgot:

Vill du inte ha

IntArray& ia

här istället?

Ja precis, tack!