我只是尝试将我的所有元素设为0
,而无需手动进行
for (i = 1; i <= n; i++)
v[i] = 0;
我在网上发现可以使用以下命令:v.clear();
,但它不起作用:
错误:请求'v'中的成员'clear',这是非类类型'int [101]'
这是我的代码:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int n,i,v[101];
int main() {
cin>>n;
for(i=1;i<=n;i++)
cin>>v[i];
v.clear();
for(i=1;i<=n;i++)
cout<<v[i]<<" ";
return 0;
}
我们有std::fill
,也可以与C样式的数组一起使用:
std::fill
您有一个数组。 C ++中的数组没有方法。您需要的是调用标准C函数memset。
例如
std::fill(std::begin(v), std::end(v), 0);
C ++中数组的索引也从0开始。因此用于循环之类
#include <cstring>
//...
std::memset( v, 0, n * sizeof( int ) );
for( i = 0; i < n; i++ )
,也可以指定std::array
之类的大小。然后,您可以使用int v[101]
来制作我所有的元素v = {0}
。例如:0
#include <iostream>
#include <array>
using namespace std;
int main() {
array<int, 101> v;
for (auto &elem : v)
cin >> elem;
v = {0};
for (auto elem : v)
cout << elem << " ";
}
,您也可以喜欢以下内容。std::array
int v[5] = {1, 2, 3, 4, 5};
int *p = v;
while (*p++ = 0, *p != 0) { };
是最好的。