简体   繁体   中英

C++ STL Vectors

I need to write a program to use an STL vector large enough to hold a user-defined number of test scores. Once all the numbers are entered, I need to average the test scores and sort them in ascending order. The issue I am having is after I put in the number of scores I am going to put in, no matter what numbers scores I put in, it reads only the first one then uses that as an average and the ascending order is pretty much that number times how many scores I put in next to each other. This is what I have so far. Thank you for any help!

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

float Average (vector<int> scores, int number);
void SortTestScores(vector<int> scores, int n);

void main(){

    vector<int> testScores;
    float averageScore, score;

    int number, i;

    cout << "Enter number of test scores: ";
    cin >> number;

    cout << "Enter test scores: ";
    for (i = 0; i < number; i++){
        cin >> score;
        testScores.push_back(score);
    }

    SortTestScores(testScores, number);

    cout << "Sorted test scores: ";
    for (i = 0; i < number; i++){
        cout << testScores.at(i);
    }

    averageScore = Average(testScores, number);

    cout << "Average test score is: " << averageScore << endl;
    system("pause");
}

//sort function

void SortTestScores(vector<int> scores, int number){
    int temp; //temporary variable
    int i, j; //loop variables
    for (i = 1; i < number; i++){
        for (j = 0; j < number - i; j++){
            if (scores.at(j) > scores.at(j+1)){
                temp = scores.at(j);
                scores.at(j) = scores.at (j+1);
                scores.at(j+1) = temp;
            }
        }
    }
}

float Average(vector<int> score, int n){
    int i; 
    float avg = 0.0;
    for (i = 0; i < n; i++){
        avg+=score.at(i);
    }
    avg = avg/n;
    return avg;
}

Change:

void SortTestScores(vector<int> scores, int number);

to

void SortTestScores(vector<int> &scores, int number);

so that the vector is passed by reference and the changes made in the function stay in the original vector. Alternatively you can use:

vector<int> SortTestScores(vector<int> scores, int number);
testScores = SortTestScores(testScores, number);

returning the sorted vector and assigning it to the original, but it will be quite inefficient. Also, if you are using c++11, you can use: std::sort(myvector.begin(), myvector.end()); for very efficient sorting (Timsort).

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