In C ++, how to write a function so that it can work with any data type?

I am learning C ++ STL using this resource: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=standardTemplateLibrary

The following function is specified here for accessing array elements:

template<typename T> void reversearr(T *begin, T *end) { 
      // We should at first decrement 'end' 
      // But only for non-empty range 
      if(begin != end) 
      { 
           end--; 
           if(begin != end) { 
                while(true) { 
                     swap(*begin, *end); 
                     begin++; 
                     if(begin == end) { 
                          break; 
                     } 
                     end--; 
                     if(begin == end) { 
                          break; 
                     } 
                } 
           } 
      } 
 } 

It works with system types of arrays, such as:

int arr[]={1,2,3,4,5}
reversearr(arr,arr+5);

But it gives the following compiler error:

"Iterator02_ReverseIterators.cpp: 39: 32: error: there is no corresponding function to call 'reverseearr (std :: vector :: iterator, std :: vector :: iterator)'"

if i use this code:

vector<int> v;
//Code to insert data in vector
reversearr(v.begin(),v.end());

How to write similar functions so that they can work as iterators?

+4
source share
3

T. , , .

, , , :

template<typename T> 
void reversearr(T begin, T end)
{
   ...
}
+4

Welp, cppreference.com , std::reverse:

:

template<class BidirIt>
void reverse(BidirIt first, BidirIt last)
{
    while ((first != last) && (first != --last)) {
        std::iter_swap(first++, last);
    }
}

BidirIt - . , .

+7

:

, * .

template<typename T> void reversearr(T begin, T end) { 

?

Because in your source code Tthere are int, but T*function parameters int*.
In my modified code Tthere are int*, but the function parameters are still int*.

And this “version” works with iterators - the syntax and semantics of iterators are chosen so that you can write general functions that work equally well with pointers or iterators.

+4
source

All Articles