简体   繁体   中英

Insertion sort c++ vectors

void insertion_sort(int *data, unsigned int n) {
    for (unsigned int uns = 1; uns < n; ++uns ) {
        int next = data[uns];

        unsigned int idx;
        for (idx = uns; idx > 0 && data[idx - 1] > next; --idx) {
            data[idx] = data[idx - 1];
        }
        data[idx] = next;   
    }
}

int main()
{
    vector<Person> crew= ucitaj_osobe("osobe.txt"); /*this reads the file osobe.tx and stores it in vector crew,this works */

       Person o;


    insertion_sort(polje, 100); // ???
    ispisi_osobe(popis); /* this prints out the vector,this works too*/

    return 0;
}

how do I send this vector to insertion sort,and sort it? please help,the code for insertion sort was implemented from another source

Your function insertion_sort is implemented to sort arrays of int and the function will not work for sorting of your vector of Person objects.

If you want to sort your vector of Person objects I suggest you use std::sort from the standard library. To use it you must implement the < operator for Person objects.

Example:

// Only to demonstrate.
struct Person {
    std::string name;
    int age;
};

// Implement according to your needs.
bool operator< (const Person& lhs, const Person& rhs) {
    return lhs.name < rhs.name;
}

int main() {
    vector<Person> crew = ucitaj_osobe("osobe.txt");

    std::sort(begin(crew), end(crew));

    ispisi_osobe(popis);

    // return 0; Unnecessary in main function.
}

Live example: http://ideone.com/YEL7IV

Note that std::sort is not guaranteed to use insertion sort.

You can pass a pointer to the array within a vector by passing the address of the first element within the vector.

insertion_sort(&crew[0], crew.size());

Your insertion_sort is designed to sort arrays of int , and only arrays of int . You cannot use it on arrays of Person .

You don't say why you want to use this insertion sort, instead of std::sort . But if you want to use it on vector of Person , you'll have to change its first argument to Person* , and pass it &crew[0], crew.size() . A better solution would be to convert it to take an std::vector<Person> directly, rather than a pointer and a size. An even better solution would be a template taking two bidirectional iterators, and invoke it with crew.begin(), crew.end() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM