Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Vector And Sort (See related posts)

// æ??述了STL里é?¢çš„Vector的用法以å?пޒåº?

   1  
   2  #include "stdafx.h"
   3  #include <string>
   4  #include <iostream>
   5  #include <algorithm>
   6  #include <vector>
   7  #include <utility>
   8  using namespace std;
   9  
  10  int main()
  11  {
  12  	vector<double> homework;
  13  
  14  	double x;
  15  	while(cin >> x)
  16  	{
  17  		homework.push_back(x);
  18  	}
  19  
  20  	vector<int>::size_type size = homework.size();
  21  	if(size == 0)
  22  	{
  23  		cout << "The size must not be Zero" << endl;
  24  		return 1;
  25  	}
  26  
  27  	sort(homework.begin(), homework.end());
  28  	vector<int>::size_type mid = size / 2;
  29  
  30  	double median = (size % 2 == 0) ? (homework[mid] + homework[mid+1]) / 2 : homework[mid];
  31  
  32  	cout << "The median is " << median << endl;
  33  }

Comments on this post

mloskot posts on Feb 08, 2006 at 07:41
I'd like to suggest you to include source of snippet you post.
The snippet above is taken (with minor changes) from the book
"Accelerated C++" by Andrew Koenig & Barbara Moo, chapter 3.2.2.

IMHO, it's a very good practice to include source of content you copy & paste somewhere.
wuhy80 posts on Feb 09, 2006 at 06:02
I will include source of content when I copy&paste from somewhere later

You need to create an account or log in to post comments to this site.


Click here to browse all 5338 code snippets

Related Posts