向量一经声明,其所有值都初始化为零。下面是一个示例代码来演示相同的功能。
null
// C++ program for displaying the default initialization // of the vector vect[] #include<bits/stdc++.h> using namespace std; int main() { // Creating a vector of size 8 vector< int > vect(8); // Printing default values for ( int i=0; i<vect.size(); i++) cout << ' ' << vect[i]; } |
输出:
0 0 0 0 0 0 0 0
如果我们希望将向量初始化为一个特定的值,比如1,该怎么办?为此,我们可以将值与向量的大小一起传递。
// C++ program for displaying specified initialization // of the vector vect[] #include<bits/stdc++.h> using namespace std; int main () { // Creates a vector of size 8 with all initial // values as 1. vector< int > vect(8, 1); for ( int i=0; i<vect.size(); i++) cout << ' ' << vect[i]; } |
输出:
1 1 1 1 1 1 1 1
如果我们希望将前4个值初始化为100,将其余6个值初始化为200,该怎么办? 一种方法是手动为向量中的每个位置提供一个值。标准模板库STL中提供的其他方法有fill和fill\n。
- 填充() “fill”函数将值“val”分配给[begin,end]范围内的所有元素,其中“begin”是初始位置,“end”是最后一个位置。
注: 请注意,范围中包括“开始”,但不包括“结束”。下面是一个“填充”示例:
// 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_n()中,我们指定开始位置、要填充的元素数和要填充的值。下面的代码演示了fill\n的用法。
// C++ program to demonstrate working of fil_n()
#include <bits/stdc++.h>
using
namespace
std;
int
main()
{
vector<
int
> vect(8);
// calling fill to initialize first four values
// to 7
fill_n(vect.begin(), 4, 7);
for
(
int
i=0; i<vect.size(); i++)
cout <<
' '
<< vect[i];
cout <<
''
;
// calling fill to initialize 3 elements from
// "begin()+3" with value 4
fill_n(vect.begin() + 3, 3, 4);
for
(
int
i=0; i<vect.size(); i++)
cout <<
' '
<< vect[i];
cout <<
''
;
return
0;
}
输出:
7 7 7 7 0 0 0 0 7 7 7 4 4 4 0 0
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END