【发布时间】:2017-10-19 11:05:37
【问题描述】:
我正在尝试编写选择排序。一切正常,但我的算法没有循环整个向量 _item 让我的 v_sorted 太短。元素排序正确。
排序.hpp
template<typename T>
std::vector<T> selection_sort(std::vector<T>);
排序.cpp
template<typename T>
std::vector<T> selection_sort(std::vector<T> _item) {
std::vector<T> v_sorted;
for(int i = 0; i < _item.size(); ++i) {
T smallest = _item[0];
for(auto const& j : _item) {
if(j < smallest) {
smallest = j;
}
}
v_sorted.push_back(smallest);
auto it = std::find(_item.begin(), _item.end(), smallest);
if (it != _item.end()) {
// to prevent moving all of items in vector
// https://stackoverflow.com/a/15998752
std::swap(*it, _item.back());
_item.pop_back();
}
}
return v_sorted;
}
template std::vector<int> selection_sort(std::vector<int> _item);
sort_tests.hpp
BOOST_AUTO_TEST_CASE(selection_sort_int)
{
std::vector<int> v_unsorted = {3, 1, 2, 7, 6};
std::vector<int> v_sorted = {1, 2, 3, 6, 7};
auto v_test = exl::selection_sort(v_unsorted);
BOOST_CHECK_EQUAL_COLLECTIONS(v_sorted.begin(), v_sorted.end(),
v_test.begin(), v_test.end());
}
此测试因Collections size mismatch: 5 != 3 而失败。任何测试都因大小不匹配而失败。循环在三次迭代后停止(在这种情况下)。提前感谢您提供任何线索。
【问题讨论】:
-
考虑
pop_back()的效果。 -
如果您不确定,请在循环开头添加
std::cout << "i = " << i << ", _item.size() = " << _item.size() << std::endl;。