Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

4
Error on Iteration Sort on Vector of Struct
Post Flair (click to view more posts with a particular flair)
Post Body

Hi. I'm new to C (3 weeks) and I'm attempting an exercise that requires a user to enter in student names along with their grades and store them as structs within a vector. Then this vector is sorted based on the grades. I know C has its own standard algorithms but I wanted to implement an insertion sort myself. Sadly, my code doesn't work. Please help me review. Thanks:

#include <iostream>
#include <vector>

struct Student
{
    std::string firstName{};
    int grade{};
};

// Insertion Sort
void sortVector(std::vector<Student>& array, int number)
{
    for (int currentIndex{ 1 }; currentIndex < number - 1;   currentIndex)
    {
        int currentValue{ array[currentIndex].grade };
        int previousIndex{ currentIndex - 1 };

        while (previousIndex >= 0 && array[previousIndex].grade > currentValue)
        {
            array.at(previousIndex   1) = array.at(previousIndex);
            --previousIndex;
        }
        array.at(previousIndex   1) = array.at(currentIndex);
    } 

// Print out names and grades
    for (const auto &element : array)
    {
        std::cout << element.firstName << " got a grade of " << element.grade << '\n';
    }
}


int main()
{
    std::cout << "How many students do you want to enter? ";
    int number{};
    std::cin >> number;

    std::vector<Student> array(number);

    for (int i{}; i < number;   i)
    {
        std::cout << "Enter a name: ";
        std::cin >> array[i].firstName;
        std::cout << "Enter a grade: ";
        std::cin >> array[i].grade;
    }

    sortVector(array, number);
}

Author
Account Strength
90%
Account Age
4 years
Verified Email
Yes
Verified Flair
No
Total Karma
2,539
Link Karma
1,150
Comment Karma
1,255
Profile updated: 5 days ago
Posts updated: 1 year ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
4 years ago