我有一個整數向量,我想繼續比較每一對,直到所有整數都進行比較。我想找到一對之間的絕對差異。例如:通過迭代遍歷遍歷一個向量內的兩個整數的比較集合
30
25
65
183
83
22
比較30和25,然後比較65和183,然後比較83和22等等。我想找到每個比較的絕對差異。數字都是隨機的,所以它必須找到對中的較大整數並從最小值中減去它。我會如何去做這件事?
我有一個整數向量,我想繼續比較每一對,直到所有整數都進行比較。我想找到一對之間的絕對差異。例如:通過迭代遍歷遍歷一個向量內的兩個整數的比較集合
30
25
65
183
83
22
比較30和25,然後比較65和183,然後比較83和22等等。我想找到每個比較的絕對差異。數字都是隨機的,所以它必須找到對中的較大整數並從最小值中減去它。我會如何去做這件事?
嘗試使用迭代器在數組索引 - 大集,你會看到的差異。
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
int main()
{
std::vector <int> xs = { 30, 25, 65, 183, 83, 22, -3 };
std::vector <int> ds;
auto print = [&]()
{
for (int d : ds)
std::cout << d << " ";
std::cout << "\n";
};
// method one (two-pass using standard algorithms)
{
std::adjacent_difference(begin(xs), end(xs), std::back_inserter(ds),
[](int a, int b) { return std::abs(b - a); }
);
bool b = false;
ds.erase(std::remove_if(begin(ds), end(ds), [&b](auto foo) { return b = !b; }), end(ds));
}
print();
// method two (one-pass for random access iterators, two-pass for sequential iterators)
ds.clear();
{
auto a = begin(xs);
auto b = next(a);
auto n = std::distance(begin(xs), end(xs))/2;
while (n--)
{
ds.emplace_back(std::abs(*b - *a));
a = next(b);
b = next(a);
}
}
print();
// method three (one-pass for sequential iterators)
ds.clear();
{
auto a = begin(xs);
auto b = next(a);
while (a != end(xs) and b != end(xs))
{
ds.emplace_back(std::abs(*b - *a));
a = next(b);
b = next(a);
}
}
print();
}
方法一隻使用標準算法,效果很好,易於閱讀。它總是進行兩遍,並且比其他兩種算法具有雙倍的內存要求。
考慮到你有隨機訪問迭代器,方法2是最有效的。它只傳遞一次,只根據需要使用盡可能多的內存。您可以通過簡單的ds.reserve(n)
和簡單分配來調整內存需求,假設ds也通過隨機訪問迭代器訪問。
方法三是一種變體,它不會對您的輸入迭代器進行任何處理,並仍然使用一次遍歷。 (它可能仍然在流迭代器上失敗,除非你記憶一些數據...大聲笑,感謝C++。)
std::vector<int> numbers;
// init...
std::vector<int> diffs(numbers.size()/2);
for (int i = 0, j = 0; i < numbers.size() - 1; ++j, i += 2) {
diffs[j] = abs(numbers[i] - numbers[i + 1]);
}
完美只是添加std :: vector數字{30,25,65,183,83,22}; std :: vector diffs(numbers.size()/ 2); –
運行這個時,我得到「矢量下標超出範圍」。以下是我使用的代碼:https://pastebin.com/x628T5hz以及數字。我不知道爲什麼它給了我這個錯誤。 – Zezima
也許它不在'if(file.is_open())'分支? – Grigory