我想通過 cpp 代碼中的索引洗掉向量中的專案。然而它太慢了
- cpp版本
long remove_cnt = 0;
for (auto &remove_idx : remove_index) {
mylist.erase(mylist.begin() (long) remove_idx - remove_cnt);
remove_cnt ;
}
- 蟒蛇版本
new_mylist = [item for i, item in enumerate(mylist) if i not in remove_index]
我希望 cpp 比 python 快。但是我的 cpp 代碼比 python 代碼慢。cpp中還有其他有效的代碼嗎?
uj5u.com熱心網友回復:
您的問題是一個很好的例子,說明為什么語言之間的 1-1 翻譯通常不起作用。
為了有效地從向量中洗掉專案,您不按索引執行此操作。假設您通過評估某些條件(謂詞)在 python 中獲得了索引。您可以在 C 中直接使用此謂詞。假設您要洗掉所有 int > 4,那么代碼如下所示:
#include <algorithm>
#include <iostream>
#include <vector>
bool greater_then_4(const int value)
{
return value > 4;
}
int main()
{
std::vector<int> values{ 1, 2, 3, 4, 5, 6, 7, 8 };
// https://en.cppreference.com/w/cpp/algorithm/remove
// remove all values greater then 4. remove will actually move all those values till the end
auto it = std::remove_if(values.begin(), values.end(), greater_then_4);
// shrink the vector to only include the items not matching the predicate
values.erase(it, values.end());
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/526404.html
上一篇:嘗試遍歷陣列并注釋它們
