RSS Forums RSS
Please support our C++ advertiser: Programming Forums

Please help me with arrays

Join Date: Sep 2004
Posts: 6,576
Reputation: Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of 
Rep Power: 31
Solved Threads: 499
Super Moderator
Narue's Avatar
Narue Narue is offline Offline
Expert Meanie

Re: Please help me with arrays

  #5  
Jul 27th, 2005
>when I try to use functions to make a program, i do not know how to use arrays
On the surface, nothing changes. You declare an array as a function parameter the same way. The only difference is that you don't need the size, and it's a good idea to pass the size as a separate parameter:
#include <iostream>

void print_array ( int a[], int size )
{
  for ( int i = 0; i < size; i++ )
    std::cout<< a[i] <<'\n';
}

int main()
{
  int a[] = {1,2,3,4,5};

  print_array ( a, 5 );
}
>I am lost on how to find that duplicate!
Rash's suggestion is the simplest (and you should use it for now), but far from the most efficient. Just as a taste of the other options, you can sort the array and then check adjacent values to see if they're the same, or you can use an existence table:
#include <iostream>

template <typename T, int sz>
char (&array(T(&)[sz]))[sz];

void print_duplicates ( int a[], int size )
{
  int exist[10] = {0};

  for ( int i = 0; i < size; i++ )
    ++exist[a[i]];

  for ( int i = 0; i < sizeof array ( exist ); i++ ) {
    if ( exist[i] > 1 )
      std::cout<< i <<" is duplicated "
        << exist[i] - 1 <<" times\n";
  }
}

int main()
{
  int a[] = {5,4,7,6,5,6,7,8,9,3,4,5,6,7,8};

  print_duplicates ( a, sizeof array ( a ) );
}
An existence table is an array of counters, where the value in the original array is the index. By using a[0] as the index for exist, exist[5] is incremented. This is not an good method when the possible ranges are big because you need an array that can hold every possible value, but other methods (such as using a std::map can be generalized quite nicely, though you lose the linear performance.
I'm here to prove you wrong.
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 12:26 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC