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

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 short	stringID;
	unsigned short	stringLen;
	dchar			*pString;

	bool operator< (const _string_info& str_info) const
	{
		return stringID < str_info.stringID;
	}
}STRING_INFO;

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

std::vector<STRING_INFO> m_strVec
std::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>

注意其中的类型转换






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值