Advertisement
NoMatchFound

Array of structs: dinamic allocation (.cpp)

Dec 13th, 2011
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3. #include "dinalloc.h"
  4.  
  5. using namespace std;
  6.  
  7. // returns -1 if the element 'str' doesn't exist in the array
  8. // otherwise it returns the position of the element
  9. int exist(hi *v, int n, str s) {
  10.     int i = 0;
  11.     while ((strcmp(v[i].name, s) != 0) && (i < n))
  12.         i++;
  13.  
  14.     if (i == n)
  15.         return -1;
  16.     else
  17.         return i;
  18. }
  19.  
  20. void loadHistogram(hi *v, int &n) {
  21.     int newcap = 0; // number of the item without duplicates
  22.     for (int i = 0; i < n; i++) {
  23.         str s;
  24.         cout << "Enter a name: ";
  25.         cin >> s;
  26.  
  27.         if (exist(v, n, s) == -1) { // if not exist it is a new item
  28.             strcpy(v[newcap].name, s);
  29.             v[newcap].cnt = 1;
  30.             newcap++;
  31.         } else // otherwise it exists, so increase the counter
  32.             v[exist(v, n, s)].cnt++;
  33.     }
  34.  
  35.     n = newcap; // set the array cap with the real number of items (without duplicates)
  36. }
  37.  
  38. void printHistogram(hi *v, int n) {
  39.     for (int i = 0; i < n; i++) {
  40.         cout << v[i].name << "\t\t" << v[i].cnt << " ";
  41.  
  42.         for (int j = 0; j < v[i].cnt; j++)
  43.             cout << "o";
  44.         cout << endl;
  45.     }
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement