如果我想使用std::list
並且插入到列表中的新元素將被插入到與比較函數相關的正確位置 - 我可以這樣做嗎? 或者我必須在每次插入後使用std :: sort?我可以讓std :: list按順序插入新元素嗎?或者必須使用std :: sort?
0
A
回答
1
你有三個選擇:
- 排序每次插入後
- 找到合適的索引和索引
- 使用std::set(推薦)
例爲第三個選項,在插入:
#include <iostream>
#include <set>
int main()
{
int myints[] = {75,23,65,42,13};
std::set<int> myset (myints,myints+5);
std::cout << "myset contains:";
for (std::set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
輸出:
MYSET包含:13 23 42 65 75
+0
爲什麼我得到一個downvote?如果有我想知道的錯誤請。 – gsamaras
3
您可以使用:
- 的std ::如果你的元素不變
- 的std ::地圖設置如果您的元素具有不可變的密鑰,但應具有可變值
- std :: list並查找插入位置
的std ::名單與標準:: LOWER_BOUND:
#include <algorithm>
#include <list>
#include <iostream>
int main()
{
std::list<int> list;
int values[] = { 7, 2, 5,3, 1, 6, 4};
for(auto i : values)
list.insert(std::lower_bound(list.begin(), list.end(), i), i);
for(auto i : list)
std::cout << i;
std::cout << '\n';
}
另外,您可以填充一個整個的std ::向量,之後對其進行排序(注:性病::排序不能性病操作::目錄::迭代器,它們不提供隨機訪問):
#include <algorithm>
#include <vector>
#include <iostream>
int main()
{
std::vector<int> vector = { 7, 2, 5,3, 1, 6, 4};
std::sort(vector.begin(), vector.end());
for(auto i : vector)
std::cout << i;
std::cout << '\n';
}
注:與插入位置的手工查找列表的表現是最差的O(N²)。
0
是的,你可以。嘗試如下所示,只需更改比較功能和類型(如果需要)。
#include <list>
inline
int compare(int& a, int&b) {
return a - b;
}
template<typename T>
void insert_in_order(std::list<T>& my_list, T element, int (*compare)(T& a, T&b)) {
auto begin = my_list.begin();
auto end = my_list.end();
while ((begin != end) &&
(compare(*begin,element) < 0) ) {
++begin;
}
my_list.insert(begin, element);
}
int main() {
std::list<int> my_list = { 5,3,2,1 };
my_list.sort(); //list == { 1,2,3,5}
insert_in_order<int>(my_list, 4, &compare); //list == {1,2,3,4,5}
}
+0
只因爲你可以不意味着你應該 –
相關問題
- 1. 順序的std :: unordered_multimap元素
- 2. std :: sort是否改變了相等元素的相對順序?
- 3. 我可以使用std :: partial_sort對std :: map進行排序嗎?
- 4. 插入元素到std ::使用構造
- 5. mem_set爲std :: map或std :: list
- 6. sort std :: list區分大小寫的元素
- 7. C++ std :: list插入問題
- 8. 使用std :: set排序std :: list
- 9. jQuery按正確順序插入元素vs detach()。sort()?
- 10. 清除std :: list元素的順序是什麼?
- 11. 在std :: multiset中維護插入順序相同的元素
- 12. 爲什麼不std :: sort在std :: list上不起作用?
- 13. 無法在迭代器的std :: set中插入元素到std :: list
- 14. std :: sort
- 15. 使用std :: make_move_iterator將std :: list <std :: unique_ptr >>插入另一個時出錯
- 16. 我可以有List(T).ForEach()嚴格按順序遍歷元素嗎?
- 17. 爲什麼只有std :: list :: sort()?
- 18. 是std :: list的多元素插入強烈異常安全?
- 19. std :: sort可能導致錯誤嗎?
- 20. 我可以扔`std :: bad_cast`嗎?
- 21. std :: initializer_list和元素的求值順序
- 22. 我可以使用std :: pair作爲std :: multimap中的鍵嗎?
- 23. 我可以容納std :: list的新插入元素的迭代器,並使用迭代器安全地清除元素嗎?
- 24. 我可以使用僞元素來插入html元素嗎?
- 25. 我可以讓std :: string使用更少的內存嗎?
- 26. std :: list的順序是否有保證?
- 27. std :: sort on std :: vector <std::string>
- 28. 可以使用std :: vector元素的地址作爲指針嗎?
- 29. std :: vector vs std :: list用於插入頻率和動態大小
- 30. 使用std :: sort和boost :: bind
每次插入後排序,或找到正確的地方開始並插入那裏。 –
或使用'std :: set'。 – songyuanyao
準確地說,當我輸入我的答案@songyuanyao時,我想到了Joachim的評論。 – gsamaras