-->

Use of array and a function to print first n eleme

2020-07-27 17:01发布

问题:

Question: I want to write an function to print an array from mth element to nth element where m<=n and if a is an array then function calling should looks like print(a+m,a+n). Noow what should be the user defined function for this case?

#include <stdio.h>
#include <iostream>

using namespace std;
/* It may be ok or not. If not then what program should write? */
void print(int a[], int n)
{
    for(int i=0;; ++i){
        if(a[i] == a[n]) break;
        printf("%d ",a[i]);
    }
}

int main()
{
    int a[6] = {1,3,5,6,8,2};
    /*We can use to sort this array of 1st n elements*/
    sort(a,a+n);
    /*if we want to use c function to sort this array 'a' for 1st 4 elements then we write*/
    sort(a,a+4);

   /*But if we want use to print 1st n elements than what should user defined function looks like?*/

    print(a,a+3); //for this function to print 1st 3 elements what should write user defined         function

    return 0;
}

回答1:

You can use pointers for such format

void print (int * begin, int * end){
  while(begin != end){
    printf("%d", *begin);
    begin++;
  }
}


回答2:

Using the std::for_each algorithm would eliminate the use of pointers and eliminate the raw loop.

It could look something like:

#include <algorithm>
#include <array>
#include <iostream>

template<std::size_t T>
void PrintArray(const std::array<int,T> arrayToPrint, const int begin, const int end)
{
    if(begin < end)
    {
        auto print = [&](const int& n){ std::cout << n << "\n";};
        std::for_each(arrayToPrint.begin() + begin, arrayToPrint.begin() + end, print);
    }
}

void CallFunction()
{
    std::array<int, 6> numberArray = {1, 3, 5, 6, 8, 2};

    PrintArray(numberArray, 0, 6);
}

(https://godbolt.org/z/FXGrCT)



回答3:

You could use iterators, specifically std::ostream_iterator, in C++ to output to the output stream:

#include <algorithm>
#include <iterator>
#include <iostream>

template <typename T>
void print(T* start, T* end)
{
    std::copy(start, end, std::ostream_iterator<T>(std::cout, " "));
}

//Call like this:
print(a, a+5);

where std::copy copies from the array, starting at start and ending at end, to the output stream. The second parameter to the std::ostream_iterator constructor is an optional delimiter string, written to the output stream after every write operation (here a space character).