Varun Garg
Varun Garg

Reputation: 595

Does redeclaration of std::container() with same name in c++ flushes out the previous data?

Given below is my code using container std::set(). Now whenever I run my while(t) loop again the data present in container std::set don't get flushed away.Why is this happening.I mean even when I am redeclaring my container how'd the values in my container got retained.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    long long int t,i,k,n,m;
    cin >> t;
    set <int> s;
    while(t--){
        cin >> n >>m;
        for(i=0;i<n;i++){
            cin >> k;
            s.insert(k);
        }
        for(i=0;i<m;i++){
            cin >> k;
            if(s.count(k)==1){
                cout << "YES" << endl;
            }
            if(s.count(k)==0){
                cout << "NO" << endl;
                s.insert(k);
            }
        }
        //s.clear();            
    }
    return 0;
}

Upvotes: 1

Views: 572

Answers (1)

Karl Nicoll
Karl Nicoll

Reputation: 16419

You're not re-declaring your std::set. You're declaring your set outside of the while loop. This means that the contents of the set will be retained until s goes out of scope (i.e. when you get to the end of main()).

You have two options for resetting the set:

#1 Move declaration of s into the while loop

int main()
{
    long long int t,i,k,n,m;
    cin >> t;
    // <-- move declaration of 's' from here.
    while(t--){
        set <int> s;  // <-- to here.
        cin >> n >>m;
        ...

#2 Uncomment s.clear() and clear the set between iterations

Simply uncomment s.clear()!

while(t--){
    cin >> n >>m;
    for(i=0;i<n;i++){
        cin >> k;
        s.insert(k);
    }
    for(i=0;i<m;i++){
        cin >> k;
        if(s.count(k)==1){
            cout << "YES" << endl;
        }
        if(s.count(k)==0){
            cout << "NO" << endl;
            s.insert(k);
        }
    }
    s.clear();          // <-- Uncomment this!
}

Upvotes: 1

Related Questions