在 c++ 中重新声明具有相同名称的 std::container() 是否会清除以前的数据
Does redeclaration of std::container() with same name in c++ flushes out the previous data?
下面是我使用容器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!
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::p mr::memory_resource 如何与 std::container 产生性能差异?
- 为什么std::{container}::template不能推导其参数类型
- 如何从 boost::container::vector<std::string>::iterator 访问索引和对象?
- 如何使用 std::transform with container without push_back.
- 在 c++ 中重新声明具有相同名称的 std::container() 是否会清除以前的数据
- 是否可以在C++中使用命名变量(例如,键和值)而不是 .first 和 .second 进行 std::map<> "for element : container" 迭代?
- 获取最接近key的std::container::迭代器
- boost::container::vector与std::vector的区别是什么?
- const decltype(*std::begin(container))& val dont make val const?
- 在 C++11 标准中是否指定 std::begin(Container&&) 返回const_iterator?
- 我可以一直使用std::inserter(container,container.end())而不是std::back_
- 从存储在 std::container 中的结构中提取元素
- 将 boost::container::boost basic_string 转换为 std::string