这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c) …Run Code Online (Sandbox Code Playgroud) 有没有之间的性能差异i++而++i如果结果不能用?
我有一个C++ 14代码.但是,当我在C++ 11中使用它时,它有一个错误const auto.如何在C++ 11中使用它?
vector<vector <int> > P;
std::vector<double> f;
vector< pair<double, vector<int> > > X;
for (int i=0;i<N;i++)
X.push_back(make_pair(f[i],P[i]));
////Sorting fitness descending order
stable_sort(X.rbegin(), X.rend());
std::stable_sort(X.rbegin(), X.rend(),
[](const auto&lhs, const auto& rhs) { return lhs.first < rhs.first; });
Run Code Online (Sandbox Code Playgroud) 是否有 Fortran 等价于 Python 的 for-else 语句?
例如,以下将数字列表排序为不同的范围。在 Python 中,它是:
absth = [1, 2, 3, 4, 5]
vals = [.1, .2, .5, 1.2, 3.5, 3.7, 16.8, 19.8, 135.60]
counts = [0] * len(absth)
for v in vals:
for i, a in enumerate(absth):
if v < a:
counts[i] += 1
break
else:
counts[-1] += 1
Run Code Online (Sandbox Code Playgroud)
在 Fortran 中,它的工作原理相同:
do iv = 1, nvals
is_in_last_absth = .true.
do ia = 1, nabsth - 1
if vals(iv) < absth(ia) then
counts(ia) = counts(ia) …Run Code Online (Sandbox Code Playgroud) c++ ×2
optimization ×2
performance ×2
auto ×1
c ×1
c++11 ×1
for-else ×1
fortran ×1
java ×1
python ×1