一些面试可能会考到的问题

来源:互联网 发布:xampp mac 编辑:程序博客网 时间:2024/04/28 11:13

std::sort用法:

std::sort的原型是这样

template<class RandomAccessIterator>   void sort(      RandomAccessIterator _First,       RandomAccessIterator _Last   );template<class RandomAccessIterator, class Pr>   void sort(      RandomAccessIterator _First,       RandomAccessIterator _Last,       BinaryPredicate _Comp   );


第一个形式默认是升序排列,需要在要排列的类中重载“<”操作符,例如:

typedef struct _string_info{unsigned shortstringID;unsigned shortstringLen;dchar*pString;bool operator< (const _string_info& str_info) const{return stringID < str_info.stringID;}}STRING_INFO;

对该结构体类型使用std::sort,应该这样使用:

std::vector<STRING_INFO> m_strVecstd::sort(m_strVec.begin(), m_strVec.end());


第二个形式是自己定义比较函数,注意在这种形式下重载“<”也是需要的,例如,要在stringID相等的情况下比较stringLen:

static bool SelfCompare(STRING_INFO &A, STRING_INFO &B){if (A.stringID < B.stringID){return true;}else if(A.stringID == B.stringID){if (A.stringLen < B.stringLen){return true;}}return false;}std::sort(m_strVec.begin(), m_strVec.end(), SelfCompare);


另外,可以使用标准库函数:

std::sort(m_strVec.begin(), m_strVec.end(), std::less<STRING_INFO>());

std::sort(m_strVec.begin(), m_strVec.end(), std::greater<STRING_INFO>());


————————————————————————————————————————————————————————————————————


shared_ptr:

“boost/shared_ptr.hpp”

一个资源可以被多个shared_ptr对象拥有,最后一个对象释放掉资源时,资源才被释放

考虑下面的例子:

class F {};class G : public F {};shared_ptr<G> sp0(new G);   // okay, template parameter G and argument G*shared_ptr<G> sp1(sp0);     // okay, template parameter G and argument shared_ptr<G>shared_ptr<F> sp2(new G);   // okay, G* convertible to F*shared_ptr<F> sp3(sp0);     // okay, template parameter F and argument shared_ptr<G>shared_ptr<F> sp4(sp2);     // okay, template parameter F and argument shared_ptr<F>shared_ptr<int> sp4(new G); // error, G* not convertible to int*shared_ptr<int> sp5(sp2);   // error, template parameter int and argument shared_ptr<F>

注意其中的类型转换






原创粉丝点击