【问题标题】:Use of array and a function to print first n elements in C [as like as sort(a+m, a+n)]使用数组和函数打印 C 中的前 n 个元素 [就像 sort(a+m, a+n)]
【发布时间】:2020-03-31 02:17:26
【问题描述】:

问题:我想编写一个函数来打印从第 m 个元素到第 n 个元素的数组,其中 m

#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;
}

【问题讨论】:

  • 原型可能类似于void print(int a[], int m, int n)void print (int * begin, int * end)。可能有数千个其他选项,但这两个非常简单。

标签: arrays c function parameters arguments


【解决方案1】:

这种格式可以使用指针

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

【讨论】:

    【解决方案2】:

    您可以在 C++ 中使用迭代器,特别是 std::ostream_iterator 来输出到输出流:

    #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);
    

    其中std::copy 从数组中复制,从startend 结束,到输出流。 std::ostream_iterator 构造函数的第二个参数是可选的分隔符字符串,在每次写入操作后写入输出流(此处为空格字符)。

    【讨论】:

      【解决方案3】:

      使用 std::for_each 算法将消除指针的使用并消除原始循环。

      它可能看起来像:

      #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)

      【讨论】:

        猜你喜欢
        • 2018-10-21
        • 2022-10-13
        • 1970-01-01
        • 2018-09-30
        • 1970-01-01
        • 2022-01-16
        • 2016-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多