Search code examples
c++arraysloopsfor-loopmemset

How can I erase all items from a vector? C++


I am just trying to make all my elements 0 without doing it manually with

for (i = 1; i <= n; i++) 
    v[i] = 0;

I found online that i can use this command: v.clear(); but it doesn't work:

error: request for member 'clear' in 'v', which is of non-class type 'int [101]'

Here's my code:

#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;
}

Solution

  • We have std::fill, that can be used with C-style arrays, too:

    std::fill(std::begin(v), std::end(v), 0);