434,849 Members | 2,361 Online
Need help? Post your question and get tips & solutions from a community of 434,849 IT Pros & Developers. It's quick & easy.

# Sort vector in ascending order, but stop prematurely

 P: n/a Hello, consider the following assignment and my code for it: /* Write a program that does the following: * Integer numbers shall be read from a textfile and stored in a std::vector. The name of the input file is to be given on the command line. * All negative values in the vector shall then be replaced with their positive counterpart, using the standard algorithm for_each. * The five smallest values in the vector shall then be found by sorting the vector, but not more than necessary. * The content of the vector is to be printed onto standard output. For full credit, all vector computations, including input and output, shall be iterator-based. Appropriate checks regarding the command line and file handling shall be done. */ #include #include #include #include #include #include using namespace std; template istream& operator>>(istream& is, vector& v) { copy(istream_iterator(is), istream_iterator(), back_inserter(v)); return is; } template ostream& operator<<(ostream& os, const vector& v) { copy(v.begin(), v.end(), ostream_iterator(os, " ")); return os; } void replace_negative(int& n) { n = abs(n); } int main(int argc, char *argv[]) { if (argc != 2) { cerr << "Wrong number of arguments." << endl; return 1; } ifstream infile(argv[1]); if (!infile) { cerr << "Failed to open file " << argv[1] << endl; return 2; } vectorv; infile.close(); cout << "Vector contents before replacing negative values " << "with their positive counterpart: " << v << endl; for_each(v.begin(), v.end(), replace_negative); cout << "Vector contents after replacing negative values " << "with their positive counterpart: " << v << endl; sort(v.begin(), v.end()); // Problem, this sorts the entire vector... cout << "Vector contents after sorting enough to place the five " << "smallest numbers first: " << v << endl; } My problem is this particular part of the assignment: * The five smallest values in the vector shall then be found by sorting the vector, but not more than necessary. The way I'm using sort it will sort the entire vector, but it sounds like the author of this assignment wants me to stop sorting after the five smallest values has been placed first in the vector, in ascending order. How do I do that?? Or am I misunderstanding what he means? I think I have been able to solve the other parts of the assignment in a proper way. I'm overloading operator>>/operator<< to enhance readability (well, I think it does), I know it's not callec for in the assignment. - Eric Jan 27 '07 #1