算法 | 描述 |
---|
fill(beg, end, val) | 将val赋值给[beg, end)之间的所有元素 |
fill_n(beg, n, val) | 将val赋值给[beg, beg+n)之间的所有元素 |
generate(beg, end, func) | 连续调用func填充[beg, end)之间的所有元素 |
generate_n(beg, n, func) | 连续调用func填充[beg, beg+n)之间的所有元素 |
💢fill and fill_n
- 🥝当我们想对一个容器的值进行填充时,我们就可以使用fill和fill_n函数。
code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
template<typename T>
void print_vector(const vector<T>& vec)
{
for (auto i_vec : vec)
{
cout << i_vec << " ";
}
cout << endl;
}
void test01()
{
int array1[5] = {0};
fill(array1, array1 + 3, 66);
for (int i_loop = 0; i_loop < sizeof(array1)/sizeof(array1[0]); i_loop++)
cout << array1[i_loop] << " ";
cout << endl;
}
void test02()
{
vector<int> vec1{2,5,6,7,9};
fill_n(vec1.begin(), 3, 33);
print_vector(vec1);
}
void main()
{
test01();
test02();
system("pause");
}
result:
66 66 66 0 0
33 33 33 7 9
code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void test01()
{
int array1[5] = { 0 };
generate(array1, array1 + 3, []() -> int { return rand() % 100; });
for (int i_loop = 0; i_loop < sizeof(array1) / sizeof(array1[0]); i_loop++)
cout << array1[i_loop] << " ";
cout << endl;
}
void main()
{
test01();
system("pause");
}
result:
💢generate and generate_n
- 🥝当你需要初始化一个容器或一个数组的元素时,而这些元素的值可以通过某种计算或函数生成,可以使用generate或generate_n。
code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print_vector(const vector<int>& vec)
{
for (auto i_vec : vec)
{
cout << i_vec << " ";
}
cout << endl;
}
void test01()
{
int array1[5] = { 0 };
generate(array1, array1 + 3, []() -> int { return rand() % 100; });
for (int i_loop = 0; i_loop < sizeof(array1) / sizeof(array1[0]); i_loop++)
cout << array1[i_loop] << " ";
cout << endl;
}
void test02()
{
vector<int> vec1(5, 66);
generate_n(vec1.begin(), 4, []() -> int { return rand() % 1000; });
print_vector(vec1);
}
void main()
{
test01();
test02();
system("pause");
}
result:
41 67 34 0 0
500 169 724 478 66