为什么InsertSort1可以而InsertSort2不行?
c++吧
全部回复
仅看楼主
level 11
gameloftyou 楼主
#include <iostream>
using namespace std;
template <class T> struct traits {
  typedef typename T::value_type value_type;
};
template <class T>
struct traits<T *>
{
  typedef T value_type;
};
template <class T>
void InsertSort1(const T &begin,const T &end)
{
  for(auto it=begin+1;it!=end;++it)
  {
    typename traits<T>::value_type value = *it;
    auto jt = it-1;
    while(value<*jt&&jt!=begin-1)
    {
      *(jt+1) = *jt;
      --jt;
    }
    *(jt+1) = value;
  }
}
template <class T>
void InsertSort2(const T &begin,const T &end)
{
  for(auto it=begin+1;it!=end;++it)
  {
    decltype(*it) value = *it;
    auto jt = it-1;
    while(value<*jt&&jt!=begin-1)
    {
      *(jt+1) = *jt;
      --jt;
    }
    *(jt+1) = value;
  }
}
int main()
{
  int a[6]{ 5, 3, 6, -2, 8, 9 };
  int b[6]{ 5, 3, 6, -2, 8, 9 };
  InsertSort1(a+0,a+6);
  InsertSort2(b+0,b+6);
  for(auto i:a) cout<<i<<",";
  cout<<endl;
  for(auto i:b) cout<<i<<",";
  return 0;
}
2013年11月15日 07点11分 1
level 9
插入排序
差评
decltype居然不能推断
差评~
2013年11月15日 07点11分 2
我试着输出了typeid(value).name(),结果是i,推断应该没问题啊
2013年11月15日 07点11分
level 11
decltype(*it) value = *it;
auto& value=*it;
这个坑爹的插入排序是什么
2013年11月15日 08点11分 3
我好像明白了什么。。。decltype推断出的都是引用类型?
2013年11月15日 08点11分
回复 gameloftyou :错了应该是左值都推断为引用类型
2013年11月15日 08点11分
回复 gameloftyou :好像也不对。。。
2013年11月15日 09点11分
回复 gameloftyou :编译错误OR运行错误?
2013年11月15日 09点11分
1