C++ Example


SUBMITTED BY: Guest

DATE: July 28, 2013, 10:20 a.m.

FORMAT: C++

SIZE: 1.7 kB

HITS: 943

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. int main()
  6. {
  7. const int NUM_PERSONS = 10;
  8. vector<string> names(NUM_PERSONS);
  9. vector<int> ages(NUM_PERSONS);
  10. for (int i = 0; i < names.size(); i++)
  11. {
  12. cout << "Enter name: ";
  13. getline (cin, names[i]);
  14. cout << "Age: ";
  15. cin >> ages[i];
  16. cin.get(); // get rid of newline left in the input buffer
  17. // (otherwise the next getline would fail)
  18. }
  19. /* star assuming that element 0 is both the lowest and the highest
  20. (after all, it is the only element checked so far, so it is both
  21. the lowest and the highest). Then, compare the rest, starting
  22. at element 1 */
  23. int pos_youngest = 0, pos_oldest = 0;
  24. for (int i = 1; i < ages.size(); i++)
  25. {
  26. if (ages[i] < ages[pos_youngest])
  27. {
  28. pos_youngest = i;
  29. }
  30. if (ages[i] > ages[pos_oldest])
  31. {
  32. pos_oldest = i;
  33. }
  34. }
  35. // Now print them
  36. cout << endl;
  37. for (int i = 0; i < names.size(); i++)
  38. {
  39. cout << names[i] << " - " << ages[i]; // no newline yet...
  40. if (i == pos_youngest)
  41. {
  42. cout << " (youngest)";
  43. }
  44. if (i == pos_oldest)
  45. {
  46. cout << " (oldest)";
  47. }
  48. cout << endl;
  49. }
  50. return 0;
  51. }

comments powered by Disqus