1

I'm trying to sort an array of numbers in ascending order and don't know whats wrong with my code (I'm completely new to vectors). I should first copy the input array (data) into an STL vector, then apply STL’s sorting algorithm to the vector, and finally copy the vector back into the array.

void STLSort(int data[],int size)
{
vector<int> a1;
a1.reserve(size);
for(int i=0;i<size;i++)
    a1[i]=data[i];
sort(a1.begin(),a1.end());
for(int i=0;i<size;i++)
    data[i]=a1[i];
}

Thanks.

4
  • Same issue: stackoverflow.com/q/4765910/51831 Commented Nov 13, 2011 at 0:51
  • ... and stackoverflow.com/q/2384137/51831 Commented Nov 13, 2011 at 0:54
  • 1
    You don't need that mess, one of the advantages of the STL algorithms is that you can apply them also to regular arrays, since pointers can act as iterators without any problem... Commented Nov 13, 2011 at 1:31
  • 1
    Alternately, instead of messing around with arrays in the first place, just use the vector and pass it around as needed. You will save yourself many more headaches. Commented Nov 13, 2011 at 2:32

2 Answers 2

4

You can sort the range directly:

void sort_me(int * arr, unsigned int size)
{
  std::sort(arr, arr + size);
}

int main()
{
  int a[] = { 3, 11, 7 };
  sort_me(a, sizeof(a)/sizeof(int));

  // or even just in-place:
  int b[] = { 12, -1, 88, 0 };
  std::sort(b, b + sizeof(b)/sizeof(int));
}

Even more hip: a template:

template <typename T, unsigned int N>
void sort_me_v2(T (&arr)[N])
{
  std::sort(arr, arr + N);
}

int main()
{
  int c[] = { -1, 2, -3, 4 };
  sort_me_v2(c);
}
Sign up to request clarification or add additional context in comments.

Comments

2
a1.reserve(size);

This allocates place for the items, but does not change the size() of the vector. In effect, end() is the same as begin() so you're sorting an empty vector. You should use

a1.resize(size);

4 Comments

In fact he won't reach the sort anyway, if he's lucky.
@ChristianRau: Why wouldn't he? operator[] isn't required to do bounds checking.
Oh, I guess you're right. Though it's UB, the memory is actually there so it should work in practice. I forgot the reserve.
@ChristianRau: Definitely UB and some (eg. debug) library might catch it. But a straightforward implementation probably wouldn't.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.