I used 600B - Queries about less or equal elements to test those and used the same code but with change in input and output streams.
Cin And Cout | Scanf And Printf | |
GNU C++ 5.1.0 | 358ms Submission:35214275 | 155ms Submission:35214230 |
GNU C++11 5.1.0 | 343ms Submission:35214311 | 156ms Submission:35214295 |
GNU C++14 6.4.0 | 187ms Submission:35214315 | 186ms Submission:35214352 |
GNU C++17 7.2.0 | 187ms Submission:35214359 | 187ms Submission:35214322 |
Looks like that scanf&printf is almost the same but cin&cout is slower under c++14.
Don't use cin&cout under c++14 to avoid TLE. Otherwise it is as good as scanf&printf and maybe better!
Scanf And Printf Code
#include <bits/stdc++.h>
using namespace std;
int n,m,val;
vector<int> a;
int main() {
scanf("%d%d",&n,&m);
for(int i = 0;i < n;i++){
scanf("%d",&val);
a.push_back(val);
}
sort(a.begin(),a.end());
for(int i = 0;i < m;i++){
int b;
scanf("%d",&b);
printf("%d ",upper_bound(a.begin(),a.end(),b)-a.begin());
}
return 0;
}
Cin And Cout Code
#include <bits/stdc++.h>
using namespace std;
int n,m,val;
vector<int> a;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m;
for(int i = 0;i < n;i++){
cin >> val;
a.push_back(val);
}
sort(a.begin(),a.end());
for(int i = 0;i < m;i++){
int b;
cin >> b;
cout << upper_bound(a.begin(),a.end(),b)-a.begin() << " ";
}
return 0;
}
Auto comment: topic has been updated by Adhami (previous revision, new revision, compare).
How can you prove this isn't a result of changes to vector class, or upper bound method.
It's the same code and the same input so the vector and the upper bound should do the same. Cin&Cout was obviously doing bad under c++14. It's about the double. That's my point in this blog.
Thank you for the point!
yeah that's exactly my point. You don't know if the vector makes it slower or the cin/cout.
I saw an earlier benchmark from a solely-input program, if I remember cin/cout is twice as fast as scanf/printf, but I can't find it anymore unfortunately.
EDIT: found it http://codeforces.net/blog/entry/5217
cin/cout significantly better. note the blog is more than 5 years ago, so c++14 didn't exist
That's a nice blog but I tested more than one time and I do not know how vector class can change the result while the same code on scanf version doesn't.
Looks like it is depends in c++ version and the type of the input as the blog mentioned.
I am sorry. I wasn't thinking at all earlier. You are right.
I think it would also be interesting if you tested the code without ios_base::sync_with_stdio(false); for comparison purposes :)