Compute Median of Values Stored In Vector - C++?

后端 未结 6 648
故里飘歌
故里飘歌 2020-11-29 03:40

I\'m a programming student, and for a project I\'m working on, on of the things I have to do is compute the median value of a vector of int values. I\'m to do this using onl

6条回答
  •  自闭症患者
    2020-11-29 03:51

    I'm not exactly sure what your restrictions on the user of member functions of vector are, but index access with [] or at() would make accessing elements simpler:

    median = hWScores.at(hWScores.size() / 2);
    

    You can also work with iterators like begin() + offset like you are currently doing, but then you need to first calculate the correct offset with size()/2 and add that to begin(), not the other way around. Also you need to dereference the resulting iterator to access the actual value at that point:

    median = *(hWScores.begin() + hWScores.size()/2)
    

提交回复
热议问题