C++ STL如何使用fill函数?代码示例

2021年3月23日14:51:31 发表评论 622 次浏览

"fill"函数为范围[begin, end)中的所有元素分配值" val", 其中" begin"是初始位置, " end"是最后位置。

注意 :请注意, 范围中包括"开始", 但不包括"结束"。以下是演示"fill"的示例:

// C++ program to demonstrate working of fill()
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
     vector< int > vect(8);
  
     // calling fill to initialize values in the
     // range to 4
     fill(vect.begin() + 2, vect.end() - 1, 4);
  
     for ( int i = 0; i < vect.size(); i++)
         cout << vect[i] << " " ;
  
     return 0;
}

输出如下:

0 0 4 4 4 4 4 0

我们还可以使用fill来填充数组中的值。

// C++ program to demonstrate working of fill()
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
     int arr[10];
  
     // calling fill to initialize values in the
     // range to 4
     fill(arr, arr + 10, 4);
  
     for ( int i = 0; i < 10; i++)
         cout << arr[i] << " " ;
  
     return 0;
}

输出如下:

4 4 4 4 4 4 4 4 4 4

fill list在C ++中。

// C++ program to demonstrate working of fill()
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
     list< int > ml = { 10, 20, 30 };
  
     fill(ml.begin(), ml.end(), 4);
  
     for ( int x : ml)
         cout << x << " " ;
  
     return 0;
}

输出如下:

4 4 4

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: