How do you pass std :: array?

I tried something simple:

template<class T> array insertionSort(array<T> arr) { for (int index = 1; index < arr.size(); index++) { for (int insertion = index; insertion > 0 && array[insertion - 1] > array[insertion]; insertion--) { std::swap(array[insertion - 1], array[insertion]); } } return arr; } void main() { array<int, 10> mine = { 1, 0, 2, 9, 3, 8, 4, 7, 5, 6 }; array result = insertionSort<int>(mine); cin.get(); } 

It seems that the array requires two types of parameters ( type , as well as size ), so how do I pass it to and from a function without knowing the size in front?

+7
c ++ c ++ 11
source share
3 answers

All in all, you really don't want to go through containers! The same algorithm that works for std::array<T, N> also works for other data structures, for example, std::vector<T> or std::deque<T> . The C ++ approach in this case is to pass to the iterator and [slightly] configure the algorithm:

 template<typename BidrectionalIterator> void insertionSort(BidirectionalIterator begin, BidirectionalIterator end) { for (BidirectionalIterator it(begin); it != end; ++it) { for (BidirectionalIterator insertion(it), tmp(insertion); begin != insertion && *--tmp > *insertion; --insertion) { std::swap(*tmp, *insertion); } } } 

(I did not check that the algorithm works, but you get the idea).

Note that the algorithm intentionally sorts the sequence in place! If you want to create a sorted copy, create a copy and sort: in this way, you have the choice to do it in place or not, and not be forced to use an approach that may require excessive memory (OK, when the sequence is large, you, of course , do not want to use this algorithm, but this is a separate issue).

+20
source share

It works the same as passing an object, not knowing the type in front. You use the template parameter:

 template<class T, size_t arrSize> std::array<T, arrSize> insertionSort(std::array<T, arrSize> arr) { for (int index = 1; index < arrSize; index++) { for (int insertion = index; insertion > 0 && array[insertion - 1] > array[insertion]; insertion--) { std::swap(array[insertion - 1], array[insertion]); } } return arr; } 
+10
source share

IMO, you should just pass the size as a template parameter and use it in a loop instead of arr.size ():

 template<class T, size_t size> array<T, size> insertionSort(array<T> arr) { for (int index = 1; index < size; index++) { for (int insertion = index; insertion > 0 && array[insertion - 1] > array[insertion]; insertion--) { std::swap(array[insertion - 1], array[insertion]); } } return arr; } void main() { array<int, 10> mine; mine.fill(0); array<int, mine.size()> result = insertionSort<int, mine.size()>(mine); cin.get(); } 
+3
source share

All Articles