CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2012
    Posts
    8

    function template

    Write a function template contains that accepts an array of the parameterized type, the number of elements in the array (an integer), and a value of the parameterized type, and returns true if the value is in the array and false otherwise.

    template<class T>
    bool contains(T a[], int k, T p)
    {
    bool stat = false;
    for(int i=0; i < k; i++)
    {
    if(a[i] == p)
    {
    stat = true;
    }
    }
    return stat;
    }

    saying compiler error...help please

  2. #2
    Join Date
    Mar 2012
    Posts
    12

    Re: function template

    i think in line
    Code:
    bool contains(T a[], int k, T p)
    you can insert
    Code:
     T a[10]
    Or
    Code:
      T *a
    then malloc memory for *a

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: function template

    Quote Originally Posted by mejiac3
    saying compiler error...help please
    I suggest that you post the smallest and simplest program that demonstrates this error, and also post what is the error. From what I see, your function template could compile, so perhaps the error lies elsewhere.

    Quote Originally Posted by htuan_2005
    you can insert
    Code:
    T a[10]
    Changing the declaration of parameter a to that won't make a difference, and in fact is wrong because it hints that the array is expected to have 10 elements when there is no such restriction.

    Quote Originally Posted by htuan_2005
    then malloc memory for *a
    That does not make sense: the function is supposed to search the array to check if it contains a value. Obviously, the array must already exist, otherwise the instructions would have mentioned populating the array in the function. Furthermore, malloc may be inappropriate to create objects of type T.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured