-1
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define max 200005
struct st{
    ll index,freq,val;
}s[max];;

int main(){
    ll t;
    cin>>t;
    while(t--){
        ll n;
        cin>>n;
        ll counter[max]={0};
        for(ll i=1;i<=n;i++){
            ll x;
            cin>>x;
            s[x].val=x;
            s[x].index=i;
            s[x].freq++;
            cout<<s[x].freq<<endl;
        }
        
    }
    return 0;
}

In this code, how I will initialize struct to zero in every while loop. I have tried memset() but It is showing error. Also I created struct object in main function. But the program crashes. Please give me hints to solve the problem.

3 Answers3

2

Try this instead, its more structured, usually less error prone.

std::fill(std::begin(s), std::end(s), st({0,0,0}));

I might even be converted to memset by the compiler.

Surt
  • 15,501
  • 3
  • 23
  • 39
0

Surely there will be a better solution than this but you can add this snippet at the beginning of the while loop:

for(int j=0; j<max; j++){
    s[j].val=0;
    s[j].index=0;
    s[j].freq=0;
}

You can also consider the idea of redeclaring the struct array every time in the loop, just like this:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define max 200005
struct st{
    ll index,freq,val;
};

int main(){
    ll t;
    cin>>t;
    while(t--){
        st s[max];
        ll n;
        cin>>n;
        ll counter[max]={0};
        for(ll i=1;i<=n;i++){
            ll x;
            cin>>x;
            s[x].val=x;
            s[x].index=i;
            s[x].freq++;
            cout<<s[x].freq<<endl;
        }
        
    }
    return 0;
}
Losak
  • 26
  • 4
0
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define max 200005
struct st{
    ll index,freq,val;
};

int main(){
    ll t;
    cin>>t;
    while(t--){
        st s[max]={0};
        ll n;
        cin>>n;
        ll counter[max]={0};
        for(ll i=1;i<=n;i++){
            ll x;
            cin>>x;
            s[x].val=x;
            s[x].index=i;
            s[x].freq++;
            cout<<s[x].freq<<endl;
        }
        
    }
    return 0;
}

I did this. The problem is solved. I used dev c++ ide, that's why the code was doing problem. Thanks all