template sort function not working for double and char

I'm trying to create a template function that sorts elements of a vector by their natural order from least to greatest. Int and string appear to sort correctly but char and double do not. Can you help me understand why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
#include <vector>

using namespace std;

template<typename T>
void printVect( vector<T> vec )
{
    for(typename vector<T>::iterator itr = vec.begin(), end = vec.end();
        itr != end; itr++ )
    {
        cout << (*itr) << endl;
    }
}

template<typename T>
vector<T> sortVect( vector<T> vec )
{
    for(typename vector<T>::iterator itr = vec.begin(), end = vec.end();
        itr != end; itr++ )
    {
        typename vector<T>::iterator itq = vec.begin();
        while( itq != vec.end() )
        {
            if( (*itr) < (*itq) ){ iter_swap( itr, itq ); }
            itq++;
        }
    }
    return vec;
}

int main()
{
    vector<int> vI = {2,4,100,44,3,25,101,1};
    vector<double> vD = {44.35,234.234,55.1,2.123};
    vector<char> vC = {'b','f','Y','c','z','q'};
    vector<string> vS = {"two", "apple", "twenty", "cat", "fish", "dog" };

    vI = sortVect( vI );
    vS = sortVect( vS );

    cout << "Int Vect sorted: \n";
    printVect( vI );
    cout << "\nDouble Vect sorted: \n";
    printVect( vD );
    cout << "\nChar Vect sorted: \n";
    printVect( vC );
    cout << "\nString Vect sorted: \n";
    printVect( vS );

    return 0;
}
Last edited on
Is there a reason you're not using std::sort?

Where do you actually sort the vector<char> and vector<double>?

It's for an exercise in Allain's Jumping into C++.

I added:

vC = sortVect( vC );
vS = sortVect( vS );

below line 41. Now everything works. Thanks for catching that.
Last edited on
Topic archived. No new replies allowed.