标签:int hash find cell span 而不是 size let nts
1,指针:
未初始化的指针通常会使得程序崩溃;
在C ++中,有几种使用其零参数构造函数创建对象的方法。
m = new IntCell( ); // OK
m = new IntCell{ }; // C++11
m = new IntCell; // Preferred in this text
通常使用最后一种;
为避免内存泄漏,通常在局部变量使用完之后删除;
地址运算符&;
int main(void) { IntCell *m; m=new IntCell{0}; m->write(5); cout<<"Cell contents: "<<m->read()<<endl; delete m; system("pause"); return 0; }
IntCell具体定义 见上章
2,引用:
在C ++ 11中,我们可以有两种类型的引用:左值引用和右值引用。
右值引用作用并不明显,
string str = "hell";
string & rstr = str; // rstr is another name for str
rstr += ’o’; // changes str to "hello"
bool cond = (&str == &rstr); // true; str and rstr are same object
string & bad1 = "hello"; // illegal: "hello" is not a modifiable lvalue
string & bad2 = str + ""; // illegal: str+"" is not an lvalue
string & sub = str.substr( 0, 4 ); // illegal: str.substr( 0, 4 ) is not an lvalue
string str = "hell";
string && bad1 = "hello"; // Legal
string && bad2 = str + ""; // Legal
string && sub = str.substr( 0, 4 ); // Legal
类型后边 && 表示右值引用,一个&表左值引用;
左值引用的使用:
#1:给复杂名字重命名
学散列时用:
auto & whichList = theLists[ myhash( x, theLists.size( ) ) ];
if( find( begin( whichList ), end( whichList ), x ) !=end( whichList ) )
return false;
whichList.push_back( x );
用whichlist替代一长串,接下来就不用被写入四次
auto whichList = theLists[ myhash( x, theLists.size( ) ) ];
不会有上边那种效果,它只会copy一下theLists[ myhash( x, theLists.size( ) ) ]里的内容,然后push_back只会改变现有的,而不是原来的;
#2:循环范围的使用
给vector中的每个值+1,
for( int i = 0; i < arr.size( ); ++i )
++arr[ i ];
原始写法:x是假定向量中每个值的copy
for( auto x : arr )// broken
++x;
我们真正想要的是x是向量中每个值的另一个名称,如果x是引用,这很容易做到:
for(auto&x:arr)//适用于
++ x;
#3:避免复制
找vector中最大值:
auto x = findMax( arr );
很多情况下,只需要值而不做改变,那么引用显然会比直接复制好,
auto & x = findMax( arr );
3,参数传递:
...
标签:int hash find cell span 而不是 size let nts
原文地址:https://www.cnblogs.com/sweetlittlebaby/p/12890454.html