Geekband-job3.3

1、非变异算法与变异算法概述

非变异算法是指一系列模板函数,在不改变操作对象的前提下对元素进行处理,如查找、子序列搜索、统计、匹配等,具体有for_each、find、adjacent_find、find_first_of、count、count_if、mismatch、equal、search;变异算法指改变容器中对象的操作,有copy、swap、transform、replace、fill、generate、remove、unique、reserve、rotate、randomshuffle、partion等

2、什么时候用到typename

typename cannot be used outside a template declaration;

声明template参数时, 前缀关键字class和typename可以互换;

从属名称(dependent names): 模板(template)内出现的名称, 相依于某个模板(template)参数, 如T t;

嵌套从属名称(nested dependent names):从属名称在class内呈嵌套装, 如T::const_iterator ci;

非从属名称(non-dependent names): 不依赖任何template参数的名称, 如int value;

如果不特定指出typename, 嵌套从属名称, 有可能产生解析(parse)歧义.

任何时候在模板(template)中指涉一个嵌套从属类型名称, 需要在前一个位置, 添加关键字typename;

否则报错(GCC): error: need 'typename' before 'T::xxx' because 'T' is a dependent scope

代码

代码:

[cpp]view plaincopy

print?

/*

* BInsertSort.cpp

*

*  Created on: 2014.4.17.

*      Author: Spike

*/

#include 

#include 

#include 

usingnamespacestd;

template

voidprint2nd(constT& container) {

typenameT::const_iterator iter(container.begin());//未加typename, 报错

++iter;

intvalue = *iter;

std::cout << value;

}

intmain () {

vector vi = {1,2,3,4,5};

print2nd(vi);

return0;

}

输出:

2

例外:嵌套从属类型名称, 如果是基类列表(base class list)和成员初值列(member initialization list)中,不使用typename;

代码:

[cpp]view plaincopy

print?

/*

* BInsertSort.cpp

*

*  Created on: 2014.4.17

*      Author: Spike

*/

#include 

#include 

usingnamespacestd;

structNumber {

Number(intx) {

std::cout <<"Number = "<< x << std::endl;

}

};

template

structBase{

typedefNumber Nested;

};

template

classDerived:publicBase::Nested {//不用typename

public:

explicitDerived(intx) : Base::Nested(x) {//不用typename

typenameBase::Nested temp(7);//必须使用

}

};

intmain () {

Derived d(5);

return0;

}

输出:

[plain]view plaincopy

print?

Number = 5

Number = 7

当使用特性类(traits class)时, 必须使用typename, 如

代码:

[cpp]view plaincopy

print?

/*

* BInsertSort.cpp

*

*  Created on: 2014.4.17

*      Author: Spike

*/

#include 

#include 

usingnamespacestd;

template

voidworkWithIter(T iter) {

typedeftypenamestd::iterator_traits::value_type value_type;//使用typename

value_type temp(*iter);

std::cout <<"temp = "<< temp << std::endl;

}

intmain () {

std::array ai = {1,2,3,4,5};

std::array::iterator aiIter = ai.begin();

workWithIter(aiIter);

return0;

}

输出:

[plain]view plaincopy

print?

temp = 1

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容