下面是我使用容器 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!
}
关于c++ - 在 C++ 中重新声明具有相同名称的 std::container() 是否会清除以前的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375079/