优化代码 #include<bits/stdc++.h> using namespace std; int main(){ int n,m,k; vector<int>v; cin>>n; while(n--){ cin>>m>>k; if(m==1){ v.push_back(k); } if(m==2){ vector<int>::iterator it = find(v.begin(),v.end(),k); if(it!=v.end()) cout<<"True"<<endl; else cout<<"False"<<endl; } } }
时间: 2023-06-18 13:02:05 浏览: 69
以下是优化后的代码:
```
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, m, k;
vector<int> v;
cin >> n;
while (n--) {
cin >> m >> k;
if (m == 1) {
v.emplace_back(k);
} else if (m == 2) {
auto it = find(v.begin(), v.end(), k);
cout << (it != v.end() ? "True" : "False") << endl;
}
}
return 0;
}
```
主要的优化有:
1. 使用 `emplace_back` 替代 `push_back`,可以避免不必要的拷贝构造函数调用,提高效率;
2. 使用 `auto` 关键字自动推导变量类型,简化代码,提高可读性;
3. 对于 if-else 的判断语句,建议使用 else if,避免不必要的判断,提高效率;
4. 使用三目运算符代替 if-else 语句,简化代码,提高可读性。
相关问题
#include <bits/stdc++.h> using namespace std;
这个头文件是C++11标准引入的,它包含了所有标准库中的头文件。使用这个头文件可以方便地在一个地方包含所有需要的头文件,而不需要一个一个地包含。这个头文件通常只在竞赛中使用,因为它不是标准C++头文件,不保证在所有编译器中都能正常工作。
以下是一个使用这个头文件的示例,实现输入4个整数a、b、c、d,将它们倒序输出:
```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
cout << d << ' ' << c << ' ' << b << ' ' << a << endl;
return 0;
}
```
c++怎么添加#include<bits/stdc++.h> using namespace std;
要在C++程序中添加#include<bits/stdc++.h>和using namespace std;,只需要在程序的开头添加这两行代码即可。这两行代码的作用是包含所有标准库头文件和使用标准命名空间std。下面是一个示例程序:
```
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code here
return 0;
}
```
注意,这种方法只适用于一些编译器,如GCC和Clang。如果你使用的是其他编译器,可能需要手动包含所需的头文件。