在 c++ 中重新声明具有相同名称的 std::container() 是否会清除以前的数据

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

本文关键字:std container 是否 数据 清除 新声明 c++ 声明      更新时间:2023-10-16

下面是我使用容器std::set()的代码。现在,每当我再次运行while(t)循环时,容器std::set中的数据都不会被冲走。为什么会这样。我的意思是,即使我重新声明我的容器,我的容器中的值是如何保留的。

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

你没有重新声明你的std::set。您是在 while 循环之外声明您的集合。这意味着集合的内容将被保留,直到s超出范围(即当您到达main()末尾时)。

有两个选项可用于重置集:

#1 将s的声明移动到 while 循环中

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取消注释s.clear()并清除迭代之间的集合

只需取消注释 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!
}