zoukankan      html  css  js  c++  java
  • 8. 数组赋值函数

    题目:

    编写一个模板函数 fill,给数组a[start : end - 1]赋值 value。测试你的代码。

    思路:

    正常思路即可。当 start > end 时,进行交换,利用一下 new_swap() 函数。

    代码:

     1 #include <iostream>
     2 using namespace std;
     3 
     4 template <typename T>
     5 void new_swap(T& a, T& b) {
     6     T temp = a;
     7     a = b;
     8     b = temp;
     9 }
    10 
    11 template <typename T>
    12 void fill_array (T* a, int start, int end, const T& value) {
    13     if (start > end) {
    14         new_swap(start, end);
    15     }
    16     while (start != end) {
    17         a[start++] = value;
    18     }
    19 }
    20 
    21 int main() {
    22     int array[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    23     int start, end, value;
    24     cout << "Enter start, end, value : ";
    25     cin >> start >> end >> value;
    26 
    27     fill_array(array, start, end, value);
    28 
    29     for (auto x : array) {
    30         cout << x << " ";
    31     }
    32 
    33     return 0;
    34 }

    这里将 value 声明为常量引用,因为不修改该值,并且传引用可以提高效率。

  • 相关阅读:
    php多态简单示例
    php接口
    PHP的两种表单数据提交方式
    PHP操作数据库
    51nod 1575 Gcd and Lcm
    51 nod 1297 管理二叉树
    51 nod 1628 非波那契树
    51 nod 1211 数独 DLX
    51nod:1689 逛街
    51 nod 1203 JZPLCM
  • 原文地址:https://www.cnblogs.com/Hello-Nolan/p/12303283.html
Copyright © 2011-2022 走看看