初学者,但在网上找不到答案。。有哪位好心人能帮我看看,不甚感激
template<int SIZE>
int(&a)[SIZE] insertSort(int(&arr)[SIZE])
{
return arr;
};
void main()
{
int arr[] = {2,4,56,65,3,6,9,4,3,5,8,4,2,1,0};
insertSort(arr);//提示找不到insertSort函数,如果将函数的返回值修改一下,编译就能通过
}
迷茫2017-04-17 11:58:00
There is also a problem with the way you write the function. I found an answer on stackoverflow. I can test it myself and run it
template<size_t n>
int (&insertSort(int (&arr)[n]))[n]
{
return arr;
}
http://stackoverflow.com/a/2302395
By the way, try not to do this
void sort(const int *arr, int *sortedArr)
vector
伊谢尔伦2017-04-17 11:58:00
Since C++
is used, type safety can be achieved here without using pointers. As @wangdai said vector
. As for returns, assignments, etc., you don’t have to worry about them. The simplest way is to use out参数
#include <vector>
#include <utility>
#include <iostream>
template<class t>
void insert_sorter(std::vector<t>& array /* out */) {
/// ...
array[3] = 0xff;
}
int main() {
std::vector<int> array = {1, 2, 3, 4, 5};
insert_sorter(array);
std::cout << array.at(3) << std::endl;
}
Of course, if you have to go back to achieve the high-big effect, then do this
#include <vector>
#include <utility>
#include <iostream>
template<class t>
std::vector<t> insert_sorter(std::vector<t>& array) {
/// ...
array[3] = 0xff;
/// move 语义不会重复拷贝array的data数据
return std::move(array);
}
int main() {
std::vector<int> array = {1, 2, 3, 4, 5};
/// 这里使用了完美的移动赋值操作,是不是比`C`的方式顺眼多了
/// 不过要记住array后面不能再使用了
std::vector<int> ret = insert_sorter(array);
std::cout << ret.at(3) << std::endl;
}
Honestly, the orthodox C++
way should be
/// 按stl的范式实现自己的sort
std::sort(s.begin(), s.end(), [](int a, int b) {
return b < a;
});