Skip to content

Commit e8cb18e

Browse files
Morwennadrian17
authored andcommitted
Make dmsort work with non-default-constructible types (fixes #1) (#2)
* Make dmsort work with non-default-constructible types (fixes #1)
1 parent b36e4e2 commit e8cb18e

File tree

2 files changed

+37
-7
lines changed

2 files changed

+37
-7
lines changed

drop_merge_sort.hpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,9 @@ namespace detail {
5959
++read;
6060
++num_dropped_in_row;
6161
} else {
62-
size_t trunc_to_length = dropped.size() - num_dropped_in_row;
63-
dropped.resize(trunc_to_length);
62+
for (int i = 0; i < num_dropped_in_row; ++i) {
63+
dropped.pop_back();
64+
}
6465
read -= num_dropped_in_row;
6566

6667
--write;
@@ -126,12 +127,11 @@ namespace detail {
126127
++read;
127128
++num_dropped_in_row;
128129
} else {
129-
size_t trunc_to_length = dropped.size() - num_dropped_in_row;
130130
for (int i = 0; i < num_dropped_in_row; ++i) {
131131
--read;
132-
*read = std::move(*(dropped.end() - (i+1)));
132+
*read = std::move(*(dropped.end() - 1));
133+
dropped.pop_back();
133134
}
134-
dropped.resize(trunc_to_length);
135135

136136
--write;
137137
dropped.push_back(std::move(*write));
@@ -174,4 +174,4 @@ void dmsort(Iter begin, Iter end) {
174174
dmsort(begin, end, std::less<>());
175175
}
176176

177-
#endif // DROP_MERGE_SORT_H
177+
#endif // DROP_MERGE_SORT_H

tests.cpp

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,37 @@ void test_noncopyable(){
7676
std::cout << std::is_sorted(std::begin(tab), std::end(tab), cmp) << "\n";
7777
}
7878

79+
struct NonDefaultConstructible {
80+
NonDefaultConstructible() = delete;
81+
NonDefaultConstructible(const NonDefaultConstructible&) = delete;
82+
NonDefaultConstructible& operator=(const NonDefaultConstructible&) = delete;
83+
NonDefaultConstructible(int value) : value(value) {}
84+
NonDefaultConstructible(NonDefaultConstructible&& other) : value(other.value) {}
85+
NonDefaultConstructible& operator=(NonDefaultConstructible&& other) {
86+
value = other.value;
87+
return *this;
88+
}
89+
90+
int value;
91+
};
92+
93+
bool operator<(const NonDefaultConstructible& lhs, const NonDefaultConstructible& rhs) {
94+
return lhs.value < rhs.value;
95+
}
96+
97+
void test_non_default_constructible(){
98+
std::vector<NonDefaultConstructible> tab;
99+
for(int i = 0; i < 10; ++i)
100+
tab.push_back(NonDefaultConstructible(-i));
101+
dmsort(tab.begin(), tab.end());
102+
for(auto &e : tab)
103+
std::cout << e.value << " ";
104+
std::cout << "\n";
105+
std::cout << std::is_sorted(std::begin(tab), std::end(tab)) << "\n";
106+
}
107+
79108
int main(){
80109
test_counts();
81110
test_noncopyable();
82-
}
111+
test_non_default_constructible();
112+
}

0 commit comments

Comments
 (0)