大家都开始C++0x了,我也来凑热闹,今天的主题是《调侃rvalue-reference》

Jinhao 2009-07-06 04:45:05
加精
和所有的故事一样,先来一个起因。

话说从C到C++,都有左值和右值的概念,来满足语义的需要。这与变量/对象无关,是用来解释一个表达式的类型。

int foo();
int *p = &foo(); //#1
p = &1; //#2


明显地,右值不能取地址。在C++中,只有const-ref才能绑定右值。例如

int &a = 0; //错误
const int &b = 0; //正确


这样看起来,右值是无法被修改的,但事实上,右值是允许被修改的,但是因为绑定到const-ref则失去修改的能力。


class T
{
public:
T():i(0){}

T& set()
{
i = 5;
return *this;
}

int value() const
{
return i;
}
private:
int i;
};

int x = T().set().value();



x得到5,在这个临时对象结束之前,我们修改了它的值,并正确得到了这个值,然后分号之后,这个临时对象被销毁。既然临时对象能被修改为什么不能用non-const-ref绑定呢?原因很简单。

int & r = int();
r = 5; //r引用的临时对象已经失效了,分号之后就已经销毁了。
const int &cr = int();
int x = cr;


此时cr引用的临时对象仍然存在,该临时对象的生命期已经延长到和cr相同。cr什么时候结束,这个临时对象就在什么时候被销毁。但有时候只能用 const-ref绑定临时对象实在是很痛苦的。例如std::auto_ptr就是一个典型的例子。两个auto_ptr对象赋值,实参对象会把资源转移到目标对象。

std::auto_ptr<int> a(new int);
std::auto_ptr<int> b = a;

之后,b将引用动态分配的int对象,a则断开拥有权。也就是说拷贝构造函数会修改参数对象。因此,auto_ptr的拷贝构造函数和赋值操作符的参数类型都是使用的auto_ptr&而不是const auto_ptr&。而对于

std::auto_ptr<int> foo()
{
return std::auto_ptr<int>(new int);
}

std::auto_ptr<int> p = foo();

拷贝构造函数只用auto_ptr&是不行的,因为不能绑定foo()产生的临时对象,如果用const auto_ptr&则无法修改这个参数,因为auto_ptr在赋值之后必须释放以前的拥有权。这里有两种方案,一种是用mutable成员。

template<typename T>
class auto_ptr
{
public:
auto_ptr(const auto_ptr& other) throw()
:ptr(other.safe_release())
{}

auto_ptr& operator=(const auto_ptr& other) throw();
private:
T* safe_release() const throw()
{
T * ret = ptr;
ptr = 0;
return ret;
}

private:
T * mutable ptr;
};


这是不被接受的方案,auto_ptr的状态和ptr这个成员紧密相连,而auto_ptr也应该在非const的情况下状态才会改变,因此这不被接受。第二种方案,也就是标准的做法。

template<typename T>
class auto_ptr
{
public:
auto_ptr(auto_ptr& other) throw();
auto_ptr(auto_ptr_ref ref) throw();

auto_ptr& operator=(auto_ptr& other) throw();
auto_ptr& operator=(auto_ptr_ref ref) throw();
...
};


用一个auto_ptr_ref来处理参数对象是右值的情况。这相当于弥补了一个语言缺陷。

对于这样的缺陷,C++加入一种新的引用类型来弥补这个问题,现在要说的就是右值引用。
右值引用主要用来绑定右值。

int foo();
const int cfoo();
int &&r = foo();
const int &&cr = cfoo();
//同样,也能绑定左值。
int i;
int &&r = i;
const int ci;
const int&& cr = ci;


右值引用的引入使C++变得更加复杂,难以学习,但是使用右值引用会让代码变得更简单,有时甚至是难以想象。对于隐晦论者,不知道怎么看待这样的问题。

首先,右值引用有一点很特殊。具名的右值引用被当作左值,无名的右值引用则仍然是右值。
例如,


int &&r = 0; //r被当作左值看待。

int&& foo();
foo(); //foo的返回类型是右值引用,其仍然是右值。


正是因为这个特性,使右值引用变得很复杂。但是其优点将在后面Perfect Forwarding部分介绍。


右值引用的引入确立了两东西,Move Semantics和Perfect Forwarding。英文上对于两词的表达对于我们来说尚为抽象,在适当时候我会用中文来表达。

1,Move Semantics(转移语义)
转移语义不同于拷贝语义,例如,两个auto_ptr对象的赋值操作,其实就是转移资源,而不是拷贝资源。用代码表达就是

class T
{
public:
T():p(new int){}

T(T& t)
:p(t.p)
{
t.p = 0;
}

T& operator=(T& t)
{
if(this != &t)
{
delete p;
p = t.p;
t.p = 0;
}
return *this;
}
private:
int *p;
};

T a;
T b(a);
T c;
c = b;

构造a的时候会动态分配一个int对象,然后a引用这个对象。构造b的时候,调用拷贝构造函数,这时a会将那个动态分配的int对象传递给b,则自己不再引用。然后c=b的赋值,b同样会把这个int对象转移给c,而自己则不在引用。这样,这个int对象,就从a转移到了b,再转移到c,而没有拷贝这个 int对象,这就是所谓的转移语义,auto_ptr也是如此。转移语义到底有什么作用?考虑一下这个情况。

std::vector<std::string> v;

v 里面保存了很多std::string对象,push_back操作会将buffer用完,然后重新分配更大的buffer,并将老buffer上的所有 std::string对象拷贝赋值到新buffer中,这个过程是很耗时的,因为每一个新的对象会被拷贝构造,然后分配内存,将老string对象的字符buffer复制到新的string对象里,然后老的被销毁,并释放字符buffer。如果std::string支持转移语义则情况大为改观,构造时,老的string对象只需要把字符buffer转移到新的string对象即可,没有了内存分配和释放的动作,性能也会大大提高。

有人纳闷了,如果std::string也支持转移语义,那就跟auto_ptr一样了,不能用在标准的STL容器里了。其实不然,因为现在C++不支持右值引用,它的拷贝构造函数并不是auto_ptr(const auto_ptr&),而STL容器则需要有拷贝语义,也就是需要元素有T(const T&)这样的拷贝构造函数。而如果让std::string支持转移语义并不会与现存的拷贝语义发生冲突。例如,加入转移语义的 std::string看起来就像是下面这样

template <
class CharType,
class Traits=char_traits<CharType>,
class Allocator=allocator<CharType>
>
class basic_string
{
public:
basic_string(const basic_string& _Right,
size_type _Roff = 0,
size_type _Count = npos,
const allocator_type& _Al = Allocator ( )
); //拷贝构造函数

basic_string(basic_string&& _Right,
size_type _Roff = 0,
size_type _Count = npos,
const allocator_type& _Al = Allocator ( )
); //转移构造函数

basic_string& operator=(const basic_string&); //拷贝赋值操作符
basic_string& operator=(basic_string&&); //转移赋值操作符
};

其中basic_string&&就是右值引用, 可以用来绑定右值。例如

std::string foo()
{
return "Hello, World";
}

std::string str;
str = foo(); //没有了字符串的拷贝动作。


细心的人在这里也许会发现一个缺陷。假如,我们定义一个具有转移语义的类,并在这个类里面使用具有转移语义的std::string。


class T
{
public:
T(const T& other) //拷贝构造
:text(other.text)
{}

T(T&& other) //转移构造
:text(other.text)
{}

T& operator=(const T& other) //拷贝赋值操作符
{
if(this != &other)
{
text = other.text;
}
return *this;
}

T& operator=(T&& other) //转移赋值操作符
{
if(this != &other)
{
text = other.text;
}
return *this;
}
private:
std::string text;
};


在前面介绍的右值引用的一个特性,发现有什么问题了吗?这里的text成员不会调用转移构造函数和转移赋值操作符。因为在T的转移构造函数和转移赋值操作符中,参数other是有名字的右值引用,因此它被当作了左值

T(T&& other) //转移构造
:text(other.text) //调用拷贝构造函数
{}

T& operator=(T&& other) //转移赋值操作符
{
if(this != &other)
{
text = other.text; //调用拷贝赋值操作符
}
return *this;
}


也许有人立马会站出来说这是极大的隐晦。其实不然,如果知道了右值引用的特性和重载解析就不会发生这样的错误。解决这个问题的办法就是让传递给text的参数变成右值。往回看,在讲右值引用之初已经提到了一点。标准库也提供了一个move函数用来做转换。

namespace std
{
template <typename T>
typename remove_reference<T>::type&&
move(T&& a)
{
return a;
}
}

remove_reference<T>::type就是得到一个解引用的类型。然后T的转移构造函数和转移赋值操作符就写成

T(T&& other) //转移构造
:text(std::move(other.text))
{}

T& operator=(T&& other) //转移赋值操作符
{
if(this != &other)
{
text = std::move(other.text);
}
return *this;
}

通过std::move一个间接调用,使实名的右值引用转换成无名的,这样就被当作右值处理。


2,Perfect Forwarding(精确转递)
有些时候我们会设计出一种管理器,用来保存所有的对象。例如窗口类

class window
{
//...
};

然后这个管理器会有一个接口用来创建指定类型对象。

template<typename Window>
window* factory()
{
return (new Window);
}

window* w = factory<Window>();

其实这样的factory是远远不够的。因为我们有时会从class window派生。例如

class msg_window
:public window
{
public:
msg_window(const std::string& text);
};

class input_window
: public window
{
public:
input_window(std::string& text);
};

factory就会写成
template<typename Window, typename T>
window* factory(const T&);

template<typename Window, typename T>
window* factory(T&);

如果派生类的构造函数有两个参数,那factory就要重载4个版本。这可不是容易的活。现在用右值引用可以方便地解决这个问题。对于一个参数的版本

namespace std
{
template<typename T> struct identity { typedef T type; };

template<typename T>
T&& forward(typename identity<T>::type&& t)
{
return t;
}
}

template<typename Window, typename T>
window* factory(T&& t)
{
return (new Window(std::forward<T>(t)));
}

window *msg = factory<msg_window>(std::string("Hello"));
std::string text;
window *input = factory<input_window>(text);

一个factory版本就能处理两种类型的参数。是不是很方便?这完全是依靠右值引用。在这里会涉及函数模板参数的推导,对于右值引用来说,这里有一个很重要的过程。例如下面的代码

template<typename T>
void f(T&& t);

int i;
f(i); //#1
f(2); //#2

#1推导结果就是f<int&>(i),这时f的参数t类型就是int&,这就是那个重要的地方。如果模板参数T是左值引用,那T&&的类型也是左值引用,例如#1推导出来的T是 int&,然后f的参数T&&也会被转换成int&。
#2推导结果就是f<int>(i),这时f的参数t类型就是int&&

在这里std::forward看上去跟std::move差不多,但为什么需要一个identity呢?这是为了防止模板参数的推导。现在我们不考虑identity的情况。

template<typename T>
T&& forward(T&& t)
{
return t;
}

和std::move完全一样,将实名的右值引用转换为无名右值引用。在调用forward的时候,模板参数T则被编译器自动推导,这就出现问题了,例如上面的factory,我们改成forward自动推导的版本。

template<typename Window, typename T>
window* factory(T&& t)
{
return (new Window(std::forward(t)));
}

t是实名的右值引用,因此被看作是左值,则std::forward返回的也是左值。对于这种情况,下面代码就能体现出一个错误

class test_window
: public window
{
public:
test_window(const std::string&);
test_window(std::string&);
};

factory<test_window>(std::string("Hello"));

会调用test_window(std::string&)来构造test_window对象,因为没有identity版本的forward将参数推导为左值,返回的也成了左值,这并不是我们期望的,std::string("Hello")创建的是临时对象。

那 identity在这里有什么用呢?为什么能解决这个问题呢?其实它只是起到一个显式指定模板参数的作用。在有identity的版本。直接写 std::forward(t)将会抱错,无法推导模板参数,而必须显式指定,从而避免了模板参数的推导。这里借用上面的test_window来解释这一点。

template<typename Window, typename T>
window* factory(T&& t)
{
return (new Window(std::forward<T>(t)));
}

std::string text;
factory<test_window>(text); //#1
factory<test_window>(std::string("Hello")); //#2

#1,text 是左值,则factory的模板参数T为std::string&,而T&&也就是std::string&,那么参数 t的类型也是std::string&,然后std::forward<std::string&>(t)也就返回的是 std::string&,仍然是左值,那么#1就会调用test_window(std::string&)来构造 test_window,符合本意。
#2,std::string("Hello")创建了一个临时对象,则factor的模板参数T为 std::string,而T&&则为std::string&&,然后 forward<std::string&&>(t)最后返回的仍然是右值。因此调用test_window(const std::string&)构造。同样符合本意。

这里std::forward<>就执行了一个Perfect forwarding,也就是精确转递,将参数t的类型精确地转递到Window的构造上。因此factory为每种参数个数的版本,只需实现一个,而不是(N^2 - 1)个。这在写开放代码,例如库的实现尤为重要。

-完-

觉得我的故事讲的不清晰的请举右手。觉得我将的清晰的请举脑袋。
http://blog.csdn.net/Jinhao/archive/2009/05/08/4159299.aspx
...全文
1605 215 打赏 收藏 转发到动态 举报
写回复
用AI写文章
215 条回复
切换为时间正序
请发表友善的回复…
发表回复
八志爱摄影 2012-04-17
  • 打赏
  • 举报
回复
好长的文章。看得头有点晕
丽日湖畔 2012-03-31
  • 打赏
  • 举报
回复
讲得透彻,需要细嚼慢咽
feng_62 2011-07-29
  • 打赏
  • 举报
回复
新手看不懂
  • 打赏
  • 举报
回复
move 和 forward 需要经过一次函数调用,会不会损失效率?
wjlsmail 2011-05-05
  • 打赏
  • 举报
回复
“具名的右值引用被当作左值,无名的右值引用则仍然是右值。”
wjlsmail 2011-05-05
  • 打赏
  • 举报
回复
挺好,对以前未定义的行为有明确定义更好
yjukh 2010-08-12
  • 打赏
  • 举报
回复
太复杂,这样会造成很多人学不下去,转而投向Java、C#之类
wu181671643 2010-08-11
  • 打赏
  • 举报
回复
好多啊 看晕了 收藏学习。
mochhk 2010-07-07
  • 打赏
  • 举报
回复
好长~~~~~。
cxxer 2010-07-07
  • 打赏
  • 举报
回复
mark
pwangeng311 2010-07-07
  • 打赏
  • 举报
回复
mark~~~~
kiss_rule 2010-07-06
  • 打赏
  • 举报
回复
个人觉得语言只是个工具,不一定要弄的那么绕。不懂这么深,一样可以写出非常棒的程序。。个人意见!
FrankSun80 2010-07-06
  • 打赏
  • 举报
回复
好文章呀,收藏了~~~~~~
勇敢的搬砖人 2010-05-26
  • 打赏
  • 举报
回复
zwvista 2010-04-12
  • 打赏
  • 举报
回复
在C++0x最终草案中,除了传统的左值和右值,还增加了x值(右值引用对象)的新概念。


表达式根据其值的类型可分为以下三类:
lvalue:左值,即传统意义上的左值。
xvalue(expiring value):x值(中间值?),指通过“右值引用”产生的对象。
这里x可以理解为即将消失(expiring),也可理解为中间(横跨左值和右值)。
prvalue(pure rvalue):纯右值,即传统意义上的右值。
两种复合类型:
glvalue(general lvalue):泛左值,由左值和x值构成。泛左值具有动态的类型和对象属性。
rvalue:右值,由x值和纯右值构成。右值具有潜在的可移动性。
关于右值引用:
具名右值引用被视为左值。
无名右值引用被视为x值。
对函数的右值引用无论具名与否都将被视为左值。
view plaincopy to clipboardprint?
struct A {
int m;
};
A&& operator+(A, A);
A&& f();

A a;
A&& ar = a static_cast<A&&>(a);
struct A {
int m;
};
A&& operator+(A, A);
A&& f();

A a;
A&& ar = a static_cast<A&&>(a);

这里表达式 f(), f().m, static_cast<A&&>(a), 以及 a + a 都是 x值。
而表达式 ar 为 A 类型的左值。

http://blog.csdn.net/zwvista/archive/2010/04/07/5459774.aspx
bluehousedahui 2010-03-13
  • 打赏
  • 举报
回复
[Quote=引用 13 楼 zmlovelx 的回复:]
很长很强大
除了膜拜都不敢看一眼
[/Quote]
我也膜拜中!!!
rome55 2010-03-12
  • 打赏
  • 举报
回复
我接分来了啊
BT六眼飞鱼 2010-03-12
  • 打赏
  • 举报
回复
占位+接分~~吼吼
go_Michael 2010-01-19
  • 打赏
  • 举报
回复
mark
wildream 2009-11-18
  • 打赏
  • 举报
回复
晕, 这文章好长, 保存了慢慢看
加载更多回复(190)
The C++ Standard Library A Tutorial and Reference (2nd Edition)+cppstdlib-code.zip C++标准库(第二版)英文版.pdf 非扫描版+源代码 Prefaceto the SecondEdition xxiii Acknowledgments for the SecondEdition xxiv Prefaceto the FirstEdition xxv Acknowledgments for the FirstEdition xxvi 1 About This Book 1 1.1 Why This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 Before ReadingThis Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.3 Styleand Structure of the Book . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 How to ReadThis Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 1.5 Stateof the Art . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.6 Example Codeand AdditionalInformation . . . . . . . . . . . . . . . . . . . . . 5 1.7 Feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 2 Introduction to C++ and the StandardLibrary 7 2.1 Historyof the C++ Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.1.1 Common Questionsabout the C++11 Standard . . . . . . . . . . . . . . 8 2.1.2 Compatibility between C++98 and C++11 . . . . . . . . . . . . . . . . . 9 2.2 Complexity and Big-O Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 3 New LanguageFeatures 13 3.1 New C++11 Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.1.1 Important MinorSyntax Cleanups . . . . . . . . . . . . . . . . . . . . . 13 3.1.2 AutomaticType Deductionwith auto . . . . . . . . . . . . . . . . . . . 14 3.1.3 UniformInitialization and Initializer Lists . . . . . . . . . . . . . . . . . 15 3.1.4 Range-Basedfor Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 17 3.1.5 MoveSemanticsand Rvalue References . . . . . . . . . . . . . . . . . . 19 viii Contents 3.1.6 New String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 3.1.7 Keyword noexcept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 3.1.8 Keyword constexpr . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.1.9 New Template Features . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 3.1.10 Lambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 3.1.11 Keyword decltype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.1.12 New Function Declaration Syntax . . . . . . . . . . . . . . . . . . . . . 32 3.1.13 Scoped Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 3.1.14 New FundamentalData Types . . . . . . . . . . . . . . . . . . . . . . . 33 3.2 Old “New” Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 3.2.1 ExplicitInitialization for FundamentalTypes . . . . . . . . . . . . . . . 37 3.2.2 Definitionof main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 4 GeneralConcepts 39 4.1 Namespace std . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4.2 Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 4.3 Errorand ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 4.3.1 Standard ExceptionClasses. . . . . . . . . . . . . . . . . . . . . . . . . 41 4.3.2 Members of ExceptionClasses. . . . . . . . . . . . . . . . . . . . . . . 44 4.3.3 PassingExceptions with Classexception_ptr . . . . . . . . . . . . . . 52 4.3.4 Throwing Standard Exceptions . . . . . . . . . . . . . . . . . . . . . . . 53 4.3.5 Deriving from Standard ExceptionClasses. . . . . . . . . . . . . . . . . 54 4.4 CallableObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 4.5 Concurrencyand Multithreading. . . . . . . . . . . . . . . . . . . . . . . . . . . 55 4.6 Allocators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 5 Utilities 59 5.1 Pairs and Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 5.1.1 Pairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 5.1.2 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 5.1.3 I/O for Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 5.1.4 Conversions between tuple sandpairs . . . . . . . . . . . . . . . . . . 75 5.2 Smart Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 5.2.1 Classshared_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 5.2.2 Classweak_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 5.2.3 Misusing Shared Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . 89 5.2.4 Shared and WeakPointersin Detail. . . . . . . . . . . . . . . . . . . . . 92 5.2.5 Classunique_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Contents ix 5.2.6 Classunique_ptrin Detail . . . . . . . . . . . . . . . . . . . . . . . . 110 5.2.7 Classauto_ptr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 5.2.8 FinalWordsonSmart Pointers . . . . . . . . . . . . . . . . . . . . . . . 114 5.3 Numeric Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 5.4 Type Traitsand Type Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 5.4.1 Purposeof Type Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 5.4.2 Type Traitsin Detail. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125 5.4.3 ReferenceWrappers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 5.4.4 Function Type Wrappers . . . . . . . . . . . . . . . . . . . . . . . . . . 133 5.5 Auxiliary Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134 5.5.1 Processing the Minimumand Maximum. . . . . . . . . . . . . . . . . . 134 5.5.2 Swapping Two Va l u e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136 5.5.3 SupplementaryComparison Operators . . . . . . . . . . . . . . . . . . . 138 5.6 Compile-Time FractionalArithmeticwith Classratio . . . . . . . . . . . . . 140 5.7 Clocks and Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143 5.7.1 Overview of the ChronoLibrary . . . . . . . . . . . . . . . . . . . . . . 143 5.7.2 Durations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144 5.7.3 Clocks and Timepoints . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 5.7.4 Date and TimeFunctions byC and POSIX . . . . . . . . . . . . . . . . . 157 5.7.5 Blocking with Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160 5.8 Header Files , ,and . . . . . . . . . . . . . . 161 5.8.1 Definitionsin . . . . . . . . . . . . . . . . . . . . . . . . . . 161 5.8.2 Definitionsin . . . . . . . . . . . . . . . . . . . . . . . . . . 162 5.8.3 Definitionsin . . . . . . . . . . . . . . . . . . . . . . . . . . 163 6 The StandardTe m p l a t e Library 165 6.1 STL Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 6.2 Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 6.2.1 Sequence Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 6.2.2 Associative Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 6.2.3 UnorderedContainers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 6.2.4 Associative Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 6.2.5 OtherContainers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 6.2.6 Container Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 6.3 Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 6.3.1 Further Examples of UsingAssociative and UnorderedContainers . . . . 193 6.3.2 Iterator Categories. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 x Contents 6.4 Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199 6.4.1 Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203 6.4.2 Handling MultipleRanges . . . . . . . . . . . . . . . . . . . . . . . . . 207 6.5 Iterator Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 6.5.1 Insert Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210 6.5.2 Stream Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212 6.5.3 ReverseIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214 6.5.4 MoveIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 6.6 User-DefinedGenericFunctions . . . . . . . . . . . . . . . . . . . . . . . . . . . 216 6.7 ManipulatingAlgorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217 6.7.1 “Removing”Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . 218 6.7.2 ManipulatingAssociative and UnorderedContainers . . . . . . . . . . . 221 6.7.3 Algorithms versus MemberFunctions . . . . . . . . . . . . . . . . . . . 223 6.8 Functions as AlgorithmArguments . . . . . . . . . . . . . . . . . . . . . . . . . 224 6.8.1 UsingFunctions as AlgorithmArguments . . . . . . . . . . . . . . . . . 224 6.8.2 Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 6.9 UsingLambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229 6.10 Function Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 6.10.1 Definitionof Function Objects . . . . . . . . . . . . . . . . . . . . . . . 233 6.10.2 PredefinedFunction Objects . . . . . . . . . . . . . . . . . . . . . . . . 239 6.10.3 Binders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241 6.10.4 Function Objectsand Bindersversus Lambdas . . . . . . . . . . . . . . . 243 6.11 Container Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244 6.11.1 Requirements for Container Elements . . . . . . . . . . . . . . . . . . . 244 6.11.2 Va l u eSemanticsor ReferenceSemantics. . . . . . . . . . . . . . . . . . 245 6.12 Errors and Exceptions inside the STL . . . . . . . . . . . . . . . . . . . . . . . . 245 6.12.1 ErrorHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246 6.12.2 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248 6.13 Extendingthe STL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250 6.13.1 Integrating AdditionalTypes . . . . . . . . . . . . . . . . . . . . . . . . 250 6.13.2 Deriving from STL Types . . . . . . . . . . . . . . . . . . . . . . . . . . 251 7 STL Containers 253 7.1 Common Container Abilitiesand Operations . . . . . . . . . . . . . . . . . . . . 254 7.1.1 Container Abilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 7.1.2 Container Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 7.1.3 Container Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 Contents xi 7.2 Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 7.2.1 Abilitiesof Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 7.2.2 ArrayOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 7.2.3 Usingarray s as C-StyleArrays . . . . . . . . . . . . . . . . . . . . . . 267 7.2.4 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 7.2.5 TupleInterface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 7.2.6 Examples of UsingArrays . . . . . . . . . . . . . . . . . . . . . . . . . 268 7.3 Ve c t o r s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 7.3.1 Abilitiesof Ve c t o r s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 7.3.2 Ve c t o r Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 7.3.3 UsingVe c t o r sas C-StyleArrays . . . . . . . . . . . . . . . . . . . . . . 278 7.3.4 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278 7.3.5 Examples of UsingVe c t o r s . . . . . . . . . . . . . . . . . . . . . . . . . 279 7.3.6 Classvector . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 7.4 Deques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 7.4.1 Abilitiesof Deques. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 7.4.2 Deque Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 7.4.3 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 7.4.4 Examples of UsingDeques. . . . . . . . . . . . . . . . . . . . . . . . . 288 7.5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 7.5.1 Abilitiesof Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290 7.5.2 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 7.5.3 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296 7.5.4 Examples of UsingLists . . . . . . . . . . . . . . . . . . . . . . . . . . 298 7.6 Forward Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 7.6.1 Abilitiesof Forward Lists . . . . . . . . . . . . . . . . . . . . . . . . . . 300 7.6.2 Forward List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 302 7.6.3 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 7.6.4 Examples of UsingForward Lists . . . . . . . . . . . . . . . . . . . . . . 312 7.7 Sets and Multisets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314 7.7.1 Abilitiesof Sets and Multisets . . . . . . . . . . . . . . . . . . . . . . . 315 7.7.2 Setand MultisetOperations. . . . . . . . . . . . . . . . . . . . . . . . . 316 7.7.3 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 7.7.4 Examples of UsingSets and Multisets . . . . . . . . . . . . . . . . . . . 325 7.7.5 Example of Specifying the Sorting Criterion at Runtime . . . . . . . . . . 328 xii Contents 7.8 Mapsand Multimaps. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331 7.8.1 Abilitiesof Mapsand Multimaps. . . . . . . . . . . . . . . . . . . . . . 332 7.8.2 Map and Multimap Operations . . . . . . . . . . . . . . . . . . . . . . . 333 7.8.3 UsingMapsas Associative Arrays . . . . . . . . . . . . . . . . . . . . . 343 7.8.4 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345 7.8.5 Examples of UsingMapsand Multimaps. . . . . . . . . . . . . . . . . . 345 7.8.6 Example with Maps,Strings,and Sorting Criterion at Runtime . . . . . . 351 7.9 UnorderedContainers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 7.9.1 Abilitiesof UnorderedContainers . . . . . . . . . . . . . . . . . . . . . 357 7.9.2 Creating and Controlling UnorderedContainers . . . . . . . . . . . . . . 359 7.9.3 OtherOperationsfor UnorderedContainers . . . . . . . . . . . . . . . . 367 7.9.4 The Bucket Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374 7.9.5 UsingUnorderedMapsas Associative Arrays . . . . . . . . . . . . . . . 374 7.9.6 ExceptionHandling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375 7.9.7 Examples of UsingUnorderedContainers . . . . . . . . . . . . . . . . . 375 7.10 OtherSTL Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385 7.10.1 Strings as STL Containers . . . . . . . . . . . . . . . . . . . . . . . . . 385 7.10.2 Ordinary C-StyleArrays as STL Containers . . . . . . . . . . . . . . . . 386 7.11 Implementing ReferenceSemantics . . . . . . . . . . . . . . . . . . . . . . . . . 388 7.12 Whento Use WhichContainer . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392 8 STL ContainerMembersin Detail 397 8.1 Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 8.2 Create, Copy,and DestroyOperations . . . . . . . . . . . . . . . . . . . . . . . . 400 8.3 Nonmodifying Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 8.3.1 Size Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403 8.3.2 Comparison Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 404 8.3.3 Nonmodifying Operationsfor Associative and UnorderedContainers . . . 404 8.4 Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406 8.5 Direct ElementAccess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408 8.6 Operationsto Generate Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 8.7 Inserting and RemovingElements . . . . . . . . . . . . . . . . . . . . . . . . . . 411 8.7.1 Inserting Single Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 411 8.7.2 Inserting MultipleElements . . . . . . . . . . . . . . . . . . . . . . . . . 416 8.7.3 RemovingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417 8.7.4 Resizing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420 Contents xiii 8.8 Special MemberFunctions for Lists and Forward Lists . . . . . . . . . . . . . . . 420 8.8.1 Special MemberFunctions for Lists (and Forward Lists) . . . . . . . . . 420 8.8.2 Special MemberFunctions for Forward Lists Only . . . . . . . . . . . . 423 8.9 Container Policy Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427 8.9.1 Nonmodifying Policy Functions . . . . . . . . . . . . . . . . . . . . . . 427 8.9.2 ModifyingPolicy Functions . . . . . . . . . . . . . . . . . . . . . . . . 428 8.9.3 Bucket Interface for UnorderedContainers . . . . . . . . . . . . . . . . . 429 8.10 Allocator Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430 8.10.1 FundamentalAllocator Members . . . . . . . . . . . . . . . . . . . . . . 430 8.10.2 Constructorswith Optional Allocator Parameters . . . . . . . . . . . . . 430 9 STL Iterators 433 9.1 Header Files for Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 9.2 Iterator Categories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 9.2.1 Output Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433 9.2.2 Input Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435 9.2.3 Forward Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436 9.2.4 BidirectionalIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437 9.2.5 Random-Access Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . 438 9.2.6 The Incrementand DecrementProblem of Ve c t o r Iterators . . . . . . . . 440 9.3 Auxiliary Iterator Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 9.3.1 advance() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441 9.3.2 next()and prev(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 9.3.3 distance() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445 9.3.4 iter_swap() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446 9.4 Iterator Adapters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 9.4.1 ReverseIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448 9.4.2 Insert Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454 9.4.3 Stream Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460 9.4.4 MoveIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 9.5 Iterator Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466 9.5.1 WritingGenericFunctions for Iterators . . . . . . . . . . . . . . . . . . . 468 9.6 WritingUser-DefinedIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471 xiv Contents 10 STL Function Objectsand UsingLambdas 475 10.1 The Conceptof Function Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 475 10.1.1 Function Objectsas Sorting Criteria . . . . . . . . . . . . . . . . . . . . 476 10.1.2 Function Objectswith Internal State . . . . . . . . . . . . . . . . . . . . 478 10.1.3 The Return Va l u eof for_each() . . . . . . . . . . . . . . . . . . . . . 482 10.1.4 Predicatesversus Function Objects. . . . . . . . . . . . . . . . . . . . . 483 10.2 PredefinedFunction Objectsand Binders . . . . . . . . . . . . . . . . . . . . . . 486 10.2.1 PredefinedFunction Objects . . . . . . . . . . . . . . . . . . . . . . . . 486 10.2.2 Function Adapters and Binders. . . . . . . . . . . . . . . . . . . . . . . 487 10.2.3 User-DefinedFunction Objectsfor Function Adapters . . . . . . . . . . . 495 10.2.4 Deprecated Function Adapters . . . . . . . . . . . . . . . . . . . . . . . 497 10.3 UsingLambdas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499 10.3.1 Lambdas versus Binders . . . . . . . . . . . . . . . . . . . . . . . . . . 499 10.3.2 Lambdas versus StatefulFunction Objects. . . . . . . . . . . . . . . . . 500 10.3.3 Lambdas Calling Global and MemberFunctions . . . . . . . . . . . . . . 502 10.3.4 Lambdas as HashFunction, Sorting,or Equivalence Criterion . . . . . . . 504 11 STL Algorithms 505 11.1 AlgorithmHeader Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 11.2 AlgorithmOverview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505 11.2.1 A BriefIntroduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506 11.2.2 Classification of Algorithms . . . . . . . . . . . . . . . . . . . . . . . . 506 11.3 Auxiliary Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517 11.4 The for_each()Algorithm. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519 11.5 Nonmodifying Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524 11.5.1 Counting Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524 11.5.2 Minimumand Maximum. . . . . . . . . . . . . . . . . . . . . . . . . . 525 11.5.3 SearchingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528 11.5.4 Comparing Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542 11.5.5 Predicatesfor Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550 11.6 ModifyingAlgorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 11.6.1 Copying Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557 11.6.2 MovingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561 11.6.3 Transforming and Combining Elements . . . . . . . . . . . . . . . . . . 563 11.6.4 Swapping Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566 11.6.5 AssigningNew Va l u e s . . . . . . . . . . . . . . . . . . . . . . . . . . . 568 11.6.6 ReplacingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571 Contents xv 11.7 RemovingAlgorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575 11.7.1 RemovingCertain Va l u e s . . . . . . . . . . . . . . . . . . . . . . . . . . 575 11.7.2 RemovingDuplicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578 11.8 Mutating Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583 11.8.1 Reversingthe Orderof Elements . . . . . . . . . . . . . . . . . . . . . . 583 11.8.2 Rotating Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584 11.8.3 PermutingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587 11.8.4 Shuffling Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589 11.8.5 MovingElements to the Front . . . . . . . . . . . . . . . . . . . . . . . 592 11.8.6 Partition into Two Subranges . . . . . . . . . . . . . . . . . . . . . . . . 594 11.9 Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 11.9.1 Sorting AllElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596 11.9.2 Partial Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599 11.9.3 Sorting Accordingto the n th Element . . . . . . . . . . . . . . . . . . . 602 11.9.4 HeapAlgorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604 11.10 Sorted-Range Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608 11.10.1SearchingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608 11.10.2MergingElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614 11.11 Numeric Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 11.11.1Processing Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623 11.11.2Converting Relativeand Absolute Va l u e s . . . . . . . . . . . . . . . . . . 627 12 SpecialContainers 631 12.1 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632 12.1.1 The Core Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633 12.1.2 Example of UsingStacks . . . . . . . . . . . . . . . . . . . . . . . . . . 633 12.1.3 A User-DefinedStackClass. . . . . . . . . . . . . . . . . . . . . . . . . 635 12.1.4 Classstack in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . 637 12.2 Queues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638 12.2.1 The Core Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639 12.2.2 Example of UsingQueues . . . . . . . . . . . . . . . . . . . . . . . . . 640 12.2.3 A User-DefinedQueue Class . . . . . . . . . . . . . . . . . . . . . . . . 641 12.2.4 Classqueue in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . 641 12.3 PriorityQueues. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641 12.3.1 The Core Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643 12.3.2 Example of UsingPriorityQueues. . . . . . . . . . . . . . . . . . . . . 643 12.3.3 Classpriority_queue in Detail . . . . . . . . . . . . . . . . . . . . 644 xvi Contents 12.4 Container Adapters in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645 12.4.1 Type Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645 12.4.2 Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646 12.4.3 SupplementaryConstructorsfor PriorityQueues. . . . . . . . . . . . . . 646 12.4.4 Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647 12.5 Bitsets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650 12.5.1 Examples of UsingBitsets . . . . . . . . . . . . . . . . . . . . . . . . . 651 12.5.2 Classbitsetin Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . 653 13 Strings 655 13.1 Purposeof the String Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656 13.1.1 A First Example: Extractinga Temporary Filename . . . . . . . . . . . . 656 13.1.2 A Second Example: ExtractingWordsand PrintingThemBackward . . . 660 13.2 Description of the String Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 663 13.2.1 String Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663 13.2.2 OperationOverview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666 13.2.3 Constructorsand Destructor . . . . . . . . . . . . . . . . . . . . . . . . 667 13.2.4 Strings and C-Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668 13.2.5 Size and Capacity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669 13.2.6 ElementAccess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 13.2.7 Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672 13.2.8 Modifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 673 13.2.9 Substringsand String Concatenation . . . . . . . . . . . . . . . . . . . . 676 13.2.10Input/Output Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 677 13.2.11Searchingand Finding . . . . . . . . . . . . . . . . . . . . . . . . . . . 678 13.2.12The Va l u enpos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680 13.2.13Numeric Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681 13.2.14Iterator Supportfor Strings . . . . . . . . . . . . . . . . . . . . . . . . . 684 13.2.15Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689 13.2.16Performance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 13.2.17Strings and Ve c t o r s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692 13.3 String Classin Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693 13.3.1 Type Definitionsand StaticVa l u e s . . . . . . . . . . . . . . . . . . . . . 693 13.3.2 Create, Copy,and DestroyOperations . . . . . . . . . . . . . . . . . . . 694 13.3.3 Operationsfor Size and Capacity . . . . . . . . . . . . . . . . . . . . . . 696 13.3.4 Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697 13.3.5 Character Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699 13.3.6 GeneratingC-Strings and Character Arrays . . . . . . . . . . . . . . . . 700 Contents xvii 13.3.7 ModifyingOperations. . . . . . . . . . . . . . . . . . . . . . . . . . . . 700 13.3.8 Searchingand Finding . . . . . . . . . . . . . . . . . . . . . . . . . . . 708 13.3.9 Substringsand String Concatenation . . . . . . . . . . . . . . . . . . . . 711 13.3.10Input/Output Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 712 13.3.11Numeric Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713 13.3.12GeneratingIterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714 13.3.13Allocator Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715 14 RegularExpressions 717 14.1 The Regex Matchand Search Interface . . . . . . . . . . . . . . . . . . . . . . . 717 14.2 Dealingwith Subexpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720 14.3 Regex Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726 14.4 Regex Token Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727 14.5 ReplacingRegularExpressions . . . . . . . . . . . . . . . . . . . . . . . . . . . 730 14.6 Regex Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732 14.7 Regex Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735 14.8 The Regex ECMAScriptGrammar . . . . . . . . . . . . . . . . . . . . . . . . . 738 14.9 OtherGrammars . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739 14.10 BasicRegex Signaturesin Detail . . . . . . . . . . . . . . . . . . . . . . . . . . 740 15 Input/Output UsingStreamClasses 743 15.1 Common Background of I/O Streams . . . . . . . . . . . . . . . . . . . . . . . . 744 15.1.1 Stream Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744 15.1.2 Stream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744 15.1.3 Global Stream Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 745 15.1.4 Stream Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745 15.1.5 Manipulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746 15.1.6 A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746 15.2 FundamentalStream Classesand Objects. . . . . . . . . . . . . . . . . . . . . . 748 15.2.1 Classes and ClassHierarchy . . . . . . . . . . . . . . . . . . . . . . . . 748 15.2.2 Global Stream Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 751 15.2.3 Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752 15.3 Standard Stream Operators <> . . . . . . . . . . . . . . . . . . . . . . . . 753 15.3.1 Output Operator <> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754 15.3.3 Input/Output of Special Types . . . . . . . . . . . . . . . . . . . . . . . 755 xviii Contents 15.4 Stateof Streams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758 15.4.1 Constants for the Stateof Streams . . . . . . . . . . . . . . . . . . . . . 758 15.4.2 MemberFunctions Accessingthe Stateof Streams. . . . . . . . . . . . . 759 15.4.3 Stream Stateand BooleanConditions . . . . . . . . . . . . . . . . . . . 760 15.4.4 Stream Stateand Exceptions . . . . . . . . . . . . . . . . . . . . . . . . 762 15.5 Standard Input/Output Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 767 15.5.1 MemberFunctions for Input . . . . . . . . . . . . . . . . . . . . . . . . 768 15.5.2 MemberFunctions for Output . . . . . . . . . . . . . . . . . . . . . . . 771 15.5.3 Example Uses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772 15.5.4 sentryObjects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772 15.6 Manipulators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774 15.6.1 Overview of AllManipulators . . . . . . . . . . . . . . . . . . . . . . . 774 15.6.2 How ManipulatorsWork . . . . . . . . . . . . . . . . . . . . . . . . . . 776 15.6.3 User-DefinedManipulators. . . . . . . . . . . . . . . . . . . . . . . . . 777 15.7 Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779 15.7.1 Format Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779 15.7.2 Input/Output Format of BooleanVa l u e s . . . . . . . . . . . . . . . . . . 781 15.7.3 FieldWidth, Fill Character,and Adjustment . . . . . . . . . . . . . . . . 781 15.7.4 PositiveSign and UppercaseLetters . . . . . . . . . . . . . . . . . . . . 784 15.7.5 Numeric Base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785 15.7.6 Floating-Point Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . 787 15.7.7 GeneralFormatting Definitions . . . . . . . . . . . . . . . . . . . . . . . 789 15.8 Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790 15.9 File Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791 15.9.1 File Stream Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791 15.9.2 Rvalue and MoveSemanticsfor File Streams . . . . . . . . . . . . . . . 795 15.9.3 File Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796 15.9.4 RandomAccess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799 15.9.5 UsingFile Descriptors . . . . . . . . . . . . . . . . . . . . . . . . . . . 801 15.10 Stream Classesfor Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802 15.10.1String Stream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802 15.10.2MoveSemanticsfor String Streams. . . . . . . . . . . . . . . . . . . . . 806 15.10.3char* Stream Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807 15.11 Input/Output Operators for User-DefinedTypes . . . . . . . . . . . . . . . . . . . 810 15.11.1Implementing Output Operators . . . . . . . . . . . . . . . . . . . . . . 810 15.11.2Implementing Input Operators . . . . . . . . . . . . . . . . . . . . . . . 812 15.11.3Input/Output UsingAuxiliary Functions . . . . . . . . . . . . . . . . . . 814 Contents xix 15.11.4User-DefinedFormat Flags . . . . . . . . . . . . . . . . . . . . . . . . . 815 15.11.5Conventionsfor User-DefinedInput/Output Operators . . . . . . . . . . . 818 15.12 Connecting Input and Output Streams . . . . . . . . . . . . . . . . . . . . . . . . 819 15.12.1Loose Coupling Usingtie() . . . . . . . . . . . . . . . . . . . . . . . . 819 15.12.2TightCoupling UsingStream Buffers . . . . . . . . . . . . . . . . . . . 820 15.12.3Redirecting Standard Streams. . . . . . . . . . . . . . . . . . . . . . . . 822 15.12.4Streamsfor Readingand Writing. . . . . . . . . . . . . . . . . . . . . . 824 15.13 The Stream Buffer Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 826 15.13.1The Stream Buffer Interfaces . . . . . . . . . . . . . . . . . . . . . . . . 826 15.13.2Stream Buffer Iterators . . . . . . . . . . . . . . . . . . . . . . . . . . . 828 15.13.3User-DefinedStream Buffers . . . . . . . . . . . . . . . . . . . . . . . . 832 15.14 PerformanceIssues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 844 15.14.1Synchronization with C’sStandard Streams . . . . . . . . . . . . . . . . 845 15.14.2Buffering in Stream Buffers . . . . . . . . . . . . . . . . . . . . . . . . . 845 15.14.3UsingStream Buffers Directly . . . . . . . . . . . . . . . . . . . . . . . 846 16 Internationalization 849 16.1 Character Encodingsand Character Sets . . . . . . . . . . . . . . . . . . . . . . . 850 16.1.1 Multibyte and Wide-CharacterText . . . . . . . . . . . . . . . . . . . . . 850 16.1.2 Different Character Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . 851 16.1.3 Dealingwith Character Sets in C++ . . . . . . . . . . . . . . . . . . . . 852 16.1.4 Character Traits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853 16.1.5 Internationalization of Special Characters . . . . . . . . . . . . . . . . . 857 16.2 The Conceptof Locales . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857 16.2.1 UsingLocales. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858 16.2.2 Locale Facets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864 16.3 Localesin Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866 16.4 Facets in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 869 16.4.1 Numeric Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 870 16.4.2 Monetary Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874 16.4.3 Timeand Date Formatting . . . . . . . . . . . . . . . . . . . . . . . . . 884 16.4.4 Character Classification and Conversion . . . . . . . . . . . . . . . . . . 891 16.4.5 String Collation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904 16.4.6 Internationalized Messages . . . . . . . . . . . . . . . . . . . . . . . . . 905 xx Contents 17 Numerics 907 17.1 RandomNumbers and Distributions. . . . . . . . . . . . . . . . . . . . . . . . . 907 17.1.1 A First Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908 17.1.2 Engines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912 17.1.3 Enginesin Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 915 17.1.4 Distributions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917 17.1.5 Distributionsin Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . 921 17.2 Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925 17.2.1 Classcomplex in General . . . . . . . . . . . . . . . . . . . . . . . . 925 17.2.2 Examples UsingClasscomplex . . . . . . . . . . . . . . . . . . . . . 926 17.2.3 Operationsfor Complex Numbers . . . . . . . . . . . . . . . . . . . . . 928 17.2.4 Classcomplex in Detail . . . . . . . . . . . . . . . . . . . . . . . . . 935 17.3 Global Numeric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941 17.4 Va l a r r a y s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 943 18 Concurrency 945 18.1 The High-Level Interface: async() and Futures . . . . . . . . . . . . . . . . . . 946 18.1.1 A First Example Usingasync() and Futures . . . . . . . . . . . . . . . 946 18.1.2 AnExample of Waitingfor Two Tasks . . . . . . . . . . . . . . . . . . . 955 18.1.3 Shared Futures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960 18.2 The Low-Level Interface: Threadsand Promises . . . . . . . . . . . . . . . . . . 964 18.2.1 Classstd::thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 964 18.2.2 Promises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 969 18.2.3 Classpackaged_task . . . . . . . . . . . . . . . . . . . . . . . . . . 972 18.3 Startinga Thread in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973 18.3.1 async() in Detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 974 18.3.2 Futuresin Detail. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975 18.3.3 Shared Futuresin Detail. . . . . . . . . . . . . . . . . . . . . . . . . . . 976 18.3.4 Classstd::promise in Detail . . . . . . . . . . . . . . . . . . . . . . . 977 18.3.5 Classstd::packaged_task in Detail . . . . . . . . . . . . . . . . . . . 977 18.3.6 Classstd::thread in Detail . . . . . . . . . . . . . . . . . . . . . . . . 979 18.3.7 Namespace this_thread . . . . . . . . . . . . . . . . . . . . . . . . . 981 18.4 Synchronizing Threads, or the Problem of Concurrency . . . . . . . . . . . . . . 982 18.4.1 Bewareof Concurrency! . . . . . . . . . . . . . . . . . . . . . . . . . . 982 18.4.2 The Reason for the Problem of Concurrent Data Access . . . . . . . . . . 983 18.4.3 WhatExactlyCan GoWrong (the Extent of the Problem) . . . . . . . . . 983 18.4.4 The Features to Solvethe Problems . . . . . . . . . . . . . . . . . . . . . 987 Contents xxi 18.5 Mutexesand Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 989 18.5.1 UsingMutexesand Locks . . . . . . . . . . . . . . . . . . . . . . . . . . 989 18.5.2 Mutexesand Locks in Detail . . . . . . . . . . . . . . . . . . . . . . . . 998 18.5.3 Calling Oncefor MultipleThreads . . . . . . . . . . . . . . . . . . . . . 1000 18.6 ConditionVa r i a b l e s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1003 18.6.1 Purposeof ConditionVa r i a b l e s . . . . . . . . . . . . . . . . . . . . . . . 1003 18.6.2 A First Complete Example for ConditionVa r i a b l e s . . . . . . . . . . . . 1004 18.6.3 UsingConditionVa r i a b l e s to Implement a Queue for MultipleThreads . . 1006 18.6.4 ConditionVa r i a b l e s in Detail . . . . . . . . . . . . . . . . . . . . . . . . 1009 18.7 Atomics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1012 18.7.1 Example of UsingAtomics . . . . . . . . . . . . . . . . . . . . . . . . . 1012 18.7.2 Atomicsand TheirHigh-Level Interface in Detail . . . . . . . . . . . . . 1016 18.7.3 The C-StyleInterface of Atomics . . . . . . . . . . . . . . . . . . . . . . 1019 18.7.4 The Low-Level Interface of Atomics . . . . . . . . . . . . . . . . . . . . 1019 19 Allocators 1023 19.1 UsingAllocatorsas an Application Programmer . . . . . . . . . . . . . . . . . . 1023 19.2 A User-DefinedAllocator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1024 19.3 UsingAllocatorsas a LibraryProgrammer . . . . . . . . . . . . . . . . . . . . . 1026 Bibliography 1031 Newsgroups and Forums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1031 Books and Web Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1032 Index 1037 This page intentionally left blank
第1章 声明和初始化 基本类型 1.1 我该如何决定使用哪种整数类型? 1.2 为什么不精确定义标准类型的大小? 1.3 因为C语言没有精确定义类型的大小,所以我一般都用typedef定义int16和int32。然后根据实际的机器环境把它们定义为int、short、long等类型。这样看来,所有的问题都解决了,是吗? 1.4 新的64位机上的64位类型是什么样的? 指针声明 1.5 这样的声明有什么问题?char*p1,p2;我在使用p2的时候报错了。 1.6 我想声明一个指针,并为它分配一些空间,但却不行。这样的代码有什么问题?char*p;*p=malloc(10); 声明风格 1.7 怎样声明和定义全局变量和函数最好? 1.8 如何在C中实现不透明(抽象)数据类型? 1.9 如何生成“半全局变量”,就是那种只能被部分源文件中的部分函数访问的变量? 存储类型 1.10 同一个静态(static)函数或变量的所有声明都必需包含static存储类型吗? 1.11 extern在函数声明中是什么意思? 1.12 关键字auto到底有什么用途? 类型定义(typedef) 1.13 对于用户定义类型,typedef和#define有什么区别? 1.14 我似乎不能成功定义一个链表。我试过typedefstruct{char*item;NODEPTRnext;}*NODEPTR;但是编译器报了错误信息。难道在C语言中结构不能包含指向自己的指针吗? 1.15 如何定义一对相互引用的结构? 1.16 Struct{ }x1;和typedefstruct{ }x2;这两个声明有什么区别? 1.17 “typedefint(*funcptr)();”是什么意思? const限定词 1.18 我有这样一组声明:typedefchar*charp;constcharpp;为什么是p而不是它指向的字符为const? 1.19 为什么不能像下面这样在初始式和数组维度值中使用const值?constintn=5;inta[n]; 1.20 constchar*p、charconst*p和char*constp有什么区别? 复杂的声明 1.21 怎样建立和理解非常复杂的声明?例如定义一个包含N个指向返回指向字符的指针的函数的指针的数组? 1.22 如何声明返回指向同类型函数的指针的函数?我在设计一个状态机,用函数表示每种状态,每个函数都会返回一个指向下一个状态的函数的指针。可我找不到任何方法来声明这样的函数——感觉我需要一个返回指针的函数,返回的指针指向的又是返回指针的函数……,如此往复,以至无穷。 数组大小 1.23 能否声明和传入数组大小一致的局部数组,或者由其他参数指定大小的参数数组? 1.24 我在一个文件中定义了一个extern数组,然后在另一个文件中使用,为什么sizeof取不到数组的大小? 声明问题 1.25 函数只定义了一次,调用了一次,但编译器提示非法重声明了。 *1.26 main的正确定义是什么?voidmain正确吗? 1.27 我的编译器总在报函数原型不匹配的错误,可我觉得没什么问题。这是为什么? 1.28 文件中的第一个声明就报出奇怪的语法错误,可我看没什么问题。这是为什么? 1.29 为什么我的编译器不允许我定义大数组,如doublearray[256][256]? 命名空间 1.30如何判断哪些标识符可以使用,哪些被保留了? 初始化 1.31 对于没有显式初始化的变量的初始值可以作怎样的假定?如果一个全局变量初始值为“零”,它可否作为空指针或浮点零? 1.32 下面的代码为什么不能编译?intf(){chara[]="Hello,world!";} *1.33 下面的初始化有什么问题?编译器提示“invalidinitializers”或其他信息。char*p=malloc(10); 1.34 chara[]="stringliteral";和char*p="stringliteral";初始化有什么区别?当我向p[i]赋值的时候,我的程序崩溃了。 1.35 chara{[3]}="abc";是否合法? 1.36 我总算弄清楚函数指针的声明方法了,但怎样才能初始化呢? 1.37 能够初始化联合吗? 第2章 结构、联合和枚举 结构声明 2.1 structx1{ };和typedefstruct{ }x2;有什么不同? 2.2 这样的代码为什么不对?structx{ };xthestruct; 2.3 结构可以包含指向自己的指针吗? 2.4 在C语言中用什么方法实现抽象数据类型最好? *2.5 在C语言中是否有模拟继承等面向对象程序设计特性的好方法? 2.6 为什么声明externf(structx*p);给我报了一个晦涩难懂的警告信息? 2.7 我遇到这样声明结构的代码:structname{intnamelen;charnamestr[1];};然后又使用一些内存分配技巧使namestr数组用起来好像有多个元素,namelen记录了元素个数。它是怎样工作的?这样是合法的和可移植的吗? 2.8 我听说结构可以赋给变量也可以对函数传入和传出。为什么K&R1却明确说明不能这样做? 2.9 为什么不能用内建的==和!=操作符比较结构? 2.10结构传递和返回是如何实现的? 2.11 如何向接受结构参数的函数传入常量值?怎样创建无名的中间的常量结构值? 2.12 怎样从/向数据文件读/写结构? 结构填充 2.13 为什么我的编译器在结构中留下了空洞?这导致空间浪费而且无法与外部数据文件进行“二进制”读写。能否关掉填充,或者控制结构域的对齐方式? 2.14 为什么sizeof返回的值大于结构大小的期望值,是不是尾部有填充? 2.15 如何确定域在结构中的字节偏移量? 2.16 怎样在运行时用名字访问结构中的域? 2.17 C语言中有和Pascal的with等价的语句吗? 2.18 既然数组名可以用作数组的基地址,为什么对结构不能这样? 2.19 程序运行正确,但退出时却“coredump”(核心转储)了,怎么回事? 联合 2.20 结构和联合有什么区别? 2.21 有办法初始化联合吗? 2.22 有没有一种自动方法来跟踪联合的哪个域在使用? 枚举 2.23 枚举和一组预处理的#define有什么不同? 2.24 枚举可移植吗? 2.25 有什么显示枚举值符号的容易方法吗? 位域 2.26 一些结构声明中的这些冒号和数字是什么意思? 2.27 为什么人们那么喜欢用显式的掩码和位操作而不直接声明位域? 第3章 表达式 求值顺序 3.1 为什么这样的代码不行?a[i]=i++; 3.2 使用我的编译器,下面的代码inti=7;printf("%d\n",i++*i++);打印出49。不管按什么顺序计算,难道不该是56吗? 3.3 对于代码inti=3;i=i++;不同编译器给出不同的i值,有的为3,有的为4,哪个是正确的? *3.4 有这样一个巧妙的表达式:a^=b^=a^=b;它不需要临时变量就可以交换a和b的值。 3.5 可否用显式括号来强制执行我所需要的计算顺序并控制相关的副作用?就算括号不行,操作符优先级是否能够控制计算顺序呢? 3.6 可是&&和||操作符呢?我看到过类似while((c=getchar())!=EOF&&c!='\n')的代码…… 3.7 是否可以安全地认为,一旦&&和||左边的表达式已经决定了整个表达式的结果,则右边的表达式不会被求值? 3.8 为什么表达式printf("%d%d",f1(),f2());先调用了f2?我觉得逗号表达式应该确保从左到右的求值顺序。 3.9 怎样才能理解复杂表达式并避免写出未定义的表达式?“序列点”是什么? 3.10在a[i]=i++;中,如果不关心a[]的哪一个分量会被写入,这段代码就没有问题,i也的确会增加1,对吗? 3.11 人们总是说i=i++的行为是未定义的。可我刚刚在一个ANSI编译器上尝试过,其结果正如我所期望的。 3.12 我不想学习那些复杂的规则,怎样才能避免这些未定义的求值顺序问题呢? 其他的表达式问题 *3.13 ++i和i++有什么区别? 3.14 如果我不使用表达式的值,那我应该用i++还是++i来做自增呢? 3.15 我要检查一个数是不是在另外两个数之间,为什么if(abc)不行? 3.16 为什么如下的代码不对?inta=1000,b=1000;longintc=a*b; 3.17 为什么下面的代码总是给出0?doubledegC,degF;degC=5.0/9*(degF-32); 3.18 需要根据条件把一个复杂的表达式赋给两个变量中的一个。可以用下面这样的代码吗?((condition)?a:b)=complicated_expression; 3.19 我有些代码包含这样的表达式。a?b=c:d有些编译器可以接受,有些却不能。为什么? 保护规则 3.20 “semanticsof‘’changeinANSIC”的警告是什么意思? 3.21 “无符号保护”和“值保护”规则的区别在哪里? 第4章 指针 基本的指针应用 4.1 指针到底有什么好处? 4.2 我想声明一个指针并为它分配一些空间,但却不行。这些代码有什么问题呢?char*p;*p=malloc(10); 4.3 *p++自增p还是p所指向的变量? 指针操作 4.4 我用指针操作int数组的时候遇到了麻烦。 4.5 我有一个char*型指针碰巧指向一些int型变量,我想跳过它们。为什么((int*)p)++;这样的代码不行? 4.6 为什么不能对void*指针进行算术操作? 4.7 我有些解析外部结构的代码,但是它却崩溃了,显示出了“unalignedaccess”(未对齐的访问)的信息。这是什么意思? 作为函数参数的指针 4.8 我有个函数,它应该接受并初始化一个指针:voidf(int*ip){staticintdummy=5;ip=&dummy;}但是当我如下调用时:int*ip;f(ip);调用者的指针没有任何变化。 4.9 能否用void**通用指针作为参数,使函数模拟按引用传递参数? 4.10 我有一个函数externintf(int*);,它接受指向int型的指针。我怎样用引用方式传入一个常数?调用f(&5);似乎不行。 4.11 C语言可以“按引用传参”吗? 其他指针问题 4.12 我看到了用指针调用函数的不同语法形式。到底怎么回事? 4.13 通用指针类型是什么?当我把函数指针赋向void*类型的时候,编译通不过。 4.14 怎样在整型和指针之间进行转换?能否暂时把整数放入指针变量中,或者相反? *4.15 我怎样把一个int变量转换为char*型?我试了类型转换,但是不行。 第5章 空指针 空指针和空指针常量 5.1 臭名昭著的空指针到底是什么? 5.2 怎样在程序里获得一个空指针? 5.3 用缩写的指针比较“if(p)”检查空指针是否有效?如果空指针的内部表达不是0会怎样? NULL宏 5.4 NULL是什么,它是怎么定义的? 5.5 在使用非零位模式作为空指针的内部表示的机器上,NULL是如何定义的? 5.6 如果NULL定义成#defineNULL((char*)0),不就可以向函数传入不加转换的NULL了吗? 5.7 我的编译器提供的头文件中定义的NULL为0L。为什么? 5.8 NULL可以合法地用作函数指针吗? 5.9 如果NULL和0作为空指针常量是等价的,那我到底该用哪一个呢? 5.10但是如果NULL的值改变了,比如在使用非零内部空指针的机器上,用NULL(而不是0) 不是更好吗? 5.11 我曾经使用过一个编译器,不使用NULL就不能编译。 5.12 我用预处理宏#defineNullptr(type)(type*)0帮助创建正确类型的空指针。 回顾 59 5.13 这有点奇怪:NULL可以确保是0,但空(null)指针却不一定? 5.14 为什么有那么多关于空指针的疑惑?为什么这些问题如此频繁地出现? 5.15 有没有什么简单点儿的办法理解所有这些与空指针有关的东西呢? 5.16 考虑到有关空指针的所有这些困惑,要求它们的内部表示都必须为0不是更简单吗? 5.17 说真的,真有机器用非零空指针吗,或者不同类型用不同的表示? 地址0上到底有什么? 5.18 运行时的整数值0转换为指针以后一定是空指针吗? 5.19 如何访问位于机器地址0处的中断向量?如果我将指针值设为0,编译器可能会自动将它转换为非零的空指针内部表示。 5.20运行时的“nullpointerassignment”错误是什么意思?应该怎样捕捉它? 第6章 数组和指针 数组和指针的基本关系 6.1 我在一个源文件中定义了chara[6],在另一个源文件中声明了externchar*a。为什么不行? 6.2 可是我听说chara[]和char*a是等价的。是这样的吗? 6.3 那么,在C语言中“指针和数组等价”到底是什么意思? 6.4 既然它们这么不同,那为什么作为函数形参的数组和指针声明可以互换呢? 数组不能被赋值 6.5 为什么不能这样向数组赋值?externchar*getpass();charstr[10];str=getpass("Enterpassword:"); 6.6 既然不能向数组赋值,那这段代码为什么可以呢?intf(charstr[]){if(str[0]=='\0')str="none";…} 6.7 如果你不能给它赋值,那么数组如何能成为左值呢? 回顾 6.8 现实地讲,数组和指针的区别是什么? 6.9 有人跟我讲,数组不过是常指针。这样讲准确吗? 6.10 我还是很困惑。到底指针是一种数组,还是数组是一种指针? 6.11 我看到一些“搞笑”的代码,包含5["abcdef"]这样的“表达式”。这为什么是合法的C语言表达式呢? 数组的指针 6.12 既然数组引用会退化为指针,如果array是数组,那么array和&array又有什么区别呢? 6.13 如何声明一个数组的指针? 动态数组分配 6.14 如何在运行时设定数组的大小?怎样才能避免固定大小的数组? 6.15 我如何声明大小和传入的数组一样的局部数组? 6.16 如何动态分配多维数组? 6.17 有个很好的窍门,如果我这样写:intrealarray[10];int*array=&realarray[-1];我就可以把“array”当作下标从1 开始的数组。 函数和多维数组 6.18 当我向一个接受指针的指针的函数传入二维数组的时候,编译器报错了。 6.19 我怎样编写接受编译时宽度未知的二维数组的函数? 6.20 我怎样在函数参数传递时混用静态和动态多维数组? 数组的大小 6.21 当数组是函数的参数时,为什么sizeof不能正确报告数组的大小? 6.22 如何在一个文件中判断声明为extern的数组的大小(例如,数组定义和大小在另一个文件中)?sizeof操作符似乎不行。 6.23 sizeof返回的大小是以字节计算的,怎样才能判断数组中有多少个元素呢? 第7章 内存分配 基本的内存分配问题 7.1 为什么这段代码不行?char*answer;printf("Typesomething:\n");gets(answer);printf("Youtyped\"%s\"\n",answer); 7.2 我的strcat()不行。我试了下面的代码:char*s1="Hello,";char*s2="world!";char*s3=strcat(s1,s2);但是我得到了奇怪的结果。 7.3 但是strcat的文档说它接受两个char*型参数。我怎么知道(空间)分配的事情呢? *7.4 我刚才试了这样的代码:char*p;strcpy(p,"abc");它运行正常。怎么回事?为什么它没有出错? *7.5 一个指针变量分配多少内存? 7.6 我使用fgets将文件的所有行读入一个数组,为什么读入的每一行都是最后一行的内容呢? 7.7 我有个函数,本该返回一个字符串,但当它返回调用者的时候,返回的字符串却是垃圾信息。 为什么? *7.8 那么返回字符串或其他聚集的正确方法是什么呢? 调用malloc 7.9 为什么在调用malloc()时报出了“waring:assignmentofpointerfromintegerlacksacast”? 7.10为什么有些代码小心翼翼地把malloc返回的值转换为分配的指针类型? *7.11 在调用malloc()的时候,错误“不能把void*转换为int*”是什么意思? 7.12 我看到下面这样的代码:char*p=malloc(strlen(s)+1);strcpy(p,s);难道不应该是malloc((strlen(s)+1)*sizeof(char))吗? 7.13 我为malloc写了一个小小的封装函数。它为什么不行? 7.14 我想声明一个指针并向它分配一些内存,但是不行。这样的代码有什么问题?char*p;*p=malloc(10); 7.15 我如何动态分配数组? 7.16 怎样判断还有多少内存? 7.17 malloc(0)是返回空指针还是指向0个字节的指针? 7.18 我听说有的操作系统在程序使用的时候才真正分配malloc申请的内存。这合法吗? 有关malloc的问题 7.19 为什么malloc返回了离谱的指针值?我的确读过问题7.9,而且也在调用之前包含了externvoid*malloc();声明。 7.20 我用一行这样的代码分配一个巨大的数组,用于数值运算:double*array=malloc(256 *256 *sizeof(double));malloc()并没有返回空指针,但是程序运行得有些奇怪,好像改写了某些内存,或者malloc()并没有分配我申请的那么多内存。为什么? 7.21 我的PC机有8兆内存。为什么我只能分配640K左右的内存? 7.22 我的应用程序非常依赖数据结构的节点的动态分配,而malloc/free的代价成了瓶颈。我该怎么做? 7.23 我的程序总是崩溃,显然发生在malloc内部的某个地方。但是我看不出哪里有问题。是malloc有bug吗? 释放内存 7.24 动态分配的内存一旦释放之后就不能再使用,是吧? 7.25 为什么在调用free()之后指针没有变空?使用(赋值、比较)释放之后的指针有多么不安全? 7.26 当我调用malloc()为一个函数的局部指针分配内存时,我还需要用free()显式地释放吗? 7.27 我在分配一些结构,它们包含指向其他动态分配的对象的指针。我在释放结构的时候,还需要释放每一个下级指针吗? 7.28 我必须在程序退出之前释放分配的所有内存吗? 7.29 我有个程序分配了大量的内存,然后又释放了。但是从操作系统看,内存的占用率却并没有变回去。 分配内存块的大小 7.30 free()怎么知道有多少字节需要释放? 7.31 那么我能否查询malloc包,以查明可分配的最大块是多大? 7.32 为什么sizeof不能告诉我它所指的内存块的大小? 其他分配函数 7.33 (像问题6.14中那样)动态分配数组之后,还能改变它的大小吗? 7.34 向realloc()的第一个参数传入空指针合法吗?你为什么要这样做? 7.35 calloc()和malloc()有什么区别?应该用哪一个?利用calloc的零填充功能安全吗?free()可以释放calloc()分配的内存吗,还是需要一个cfree()? 7.36 alloca是什么?为什么不提倡使用它? 第8章 字符和字符串 8.1 为什么strcat(string,'!');不行? 8.2 我想检查一个字符串是否跟某个值匹配。为什么这样不行?if(string=="value") 8.3 如果我可以写chara[]="Hello,world!";那为什么不能写chara[14];a="Hello,world!"; 8.4 为什么我的strcat不行?我试了char*s1="Hello,";char*s2="world!";char*s3 =strcat(s1,s2);可得到的结果很奇怪。 8.5 chara[]="stringliteral";和char*p="stringliteral";初始化有什么区别?当我对p[i]赋值的时候,程序崩溃了。 8.6 我怎么得到与字符相对应的数字(即ASCII或其他字符集下的)值?反过来又该怎么做? 8.7 C语言有类似其他语言的"substr"(提取子串)这样的函数吗? 8.8 我将用户键入的字符串读入数组,然后再显示出来。当用户键入\n这样的序列时,为什么不能正确处理呢? 8.9 我注意到sizeof('a')是2而不是1(即不是sizeof(char)),是不是我的编译器有问题? 8.10 我正开始考虑多语言字符集的问题。是否有必要担心sizeof(char)会被定义为2,以便表达16位的字符集呢? 第9章 布尔表达式和变量 9.1 C语言中布尔值该用什么类型?为什么它不是一个标准类型?我应该用#define或enum定义真值和假值吗? 9.2 既然在C语言中所有的非零值都被看作“真”,那是不是把TRUE定义为1很危险?如果某个内建的函数或关系操作符“返回”不是1的其他值怎么办? 9.3 当p是指针时,if(p)是合法的条件表达式吗? 9.4 我该使用像TRUE和FALSE这样的符号名称还是直接用1和0来作布尔常量? 9.5 我准备使用的一个第三方头文件定义了自己的TRUE和FALSE,它们跟我已经开发的部分不兼容。我该怎么办? 第10章 C预处理器 宏定义 10.1 我想定义一些函数式的宏,例如:#definesquare(x)x*x但它们并不总是正确的。为什么? 10.2 这里有一些的预处理宏,使用它们,我可以写出更像Pascal的C代码。你觉得怎么样? 10.3 怎么写一个交换两个值的通用宏? 10.4 书写多语句宏的最好方法是什么? 10.5 用typdef和预处理宏生成用户定义类型有什么区别? 头文件 10.6 我第一次把一个程序分成多个源文件,我不知道该把什么放到.c文件,把什么放到.h文件。(“.h”到底是什么意思?) 10.7 可以在一个头文件中包含另一头文件吗? 10.8 完整的头文件搜索规则是怎样的? 10.9 我在文件的第一个声明就遇到奇怪的语法错误,但是看上去没什么问题。 10.10 我使用了来自两个不同的第三方库的头文件,它们都定义了相同的宏,如TRUE、FALSE、Min()和Max()等,但是它们的定义相互冲突,而且跟我在自己的头文件中的定义也有冲突。我该怎么办? 10.11 我在编译一个程序,看起来我好像缺少需要的一个或多个头文件。谁能发给我一份? 条件编译 10.12 怎样构造比较字符串的#if预处理表达式? 10.13 sizeof操作符可以用在#if预处理指令中吗? 10.14 我可以像这样在#define行里使用#ifdef来定义两个不同的东西吗? 10.15 对typedef的类型定义有没有类似#ifdef的东西? 10.16 我如何用#if表达式来判断机器是高字节在前还是低字节在前? 10.17 为什么在我用#ifdef关掉的代码行中报出了奇怪的语法错误? 10.18 我拿到了一些代码,里边有太多的#ifdef。我不想使用预处理器把所有的#include和#ifdef都扩展开,有什么办法只保留一种条件的代码呢? 10.19 如何列出所有的预定义宏? 奇异的处理 10.20 我有些旧代码,试图用这样的宏来构造标识符:#definePaste(a,b)a/**/b但是不行了。为什么? 10.21 我有一个旧宏:#defineCTRL(c)('c'&037)不能用了。为什么? 10.22 为什么宏#defineTRACE(n)printf("TRACE:\%d\n",n)报出警告“macroreplacementwithinastringliteral”?它似乎把TRACE(count);扩展成了printf("TRACE:\%d\count",count); 10.23 如何在宏扩展的字符串字面量中使用宏参数? 10.24 我想用ANSI的“字符串化”预处理操作符#将符号常量的值放入消息中,但它总是对宏名称而不是它的值进行字符串化。这是什么原因? 10.25 我想用预处理器做某件事情,但却不知道如何下手。 可变参数列表的宏 10.26 怎样写可变参数宏?如何用预处理器“关掉”具有可变参数的函数调用? 10.27 如何在通用的调试宏中包含__FILE__和__LINE__宏? 第11章 ANSI/ISO标准C 标准 11.1 什么是“ANSIC标准”? 11.2 如何得到一份标准的副本? *11.3 我在哪里可以找到标准的更新? 函数原型 11.4 为什么我的ANSI编译器对用float声明的参数会警告类型不匹配? 11.5 能否混用旧式的和新型的函数语法? *11.6 为什么下述声明报出了一个奇怪的警告信息“StructXdeclaredinsideparameterlist”?externintf(structx*p); 11.7 有个问题一直困扰着我,它是由这一行printf("%d",n);导致的,因为n是个longint型。难道ANSI的函数原型不能检查这种函数的参数不匹配问题吗? 11.8 我听说必须在调用printf之前包含stdio.h。为什么? const限定词 11.9 为什么不能在初始化和数组维度中使用const值?例如constintn=5;inta[n]; 11.10“constchar*p”、“charconst*p”和“char*constp”有何区别? 11.11 为什么不能向接受constchar**的函数传入char**? 11.12 我这样声明:typedefchar*charp;constcharpp;为什么是p而不是它所指向的字符为const? main()函数的使用 11.13 能否通过将main声明为void来关掉“main没有返回值”的警告? 11.14 main()的第3个参数envp是怎么回事? 11.15 我觉得把main()声明为void也不会失败,因为我调用了exit()而不是return,况且我的操作系统也忽略了程序的退出/返回状态。 *11.16 那么到底会出什么问题?真的有什么系统不支持voidmain()吗? 11.17 为什么以前流行的那些C语言书总是使用voidmain()? 11.18 在main()中调用exit(status)和返回同样的status真的等价吗? 预处理功能 11.19 我试图用ANSI“字符串化”预处理操作符'#'向信息中插入符号常量的值,但它字符串化的总是宏的名字而不是它的值。为什么? 11.20 警告信息“warning:macroreplacementwithinastringliteral”是什么意思? 11.21 为什么在我用#ifdef去掉的代码里出现了奇怪的语法错误? 11.22 #pragma是什么,有什么用? 11.23 “#pragmaonce”什么意思?我在一些头文件中看到了它。 其他的ANSIC问题 11.24 chara[3]="abc";合法吗?它是什么意思? 11.25 既然对数组的引用会退化为指针,那么,如果array是数组,array和&array之间有什么区别呢? 11.26 为什么我不能对void*指针进行算术运算? 11.27 memcpy()和memmove()有什么区别? 11.28 malloc(0)有什么用?返回一个空指针还是指向0字节的指针? 11.29 为什么ANSI标准规定了外部标识符的长度和大小写限制? 11.30 noalias是怎么回事?在它身上发生了什么? 老的或非标准的编译器 11.31 为什么我的编译器对最简单的测试程序都报出了一大堆的语法错误?对这段代码的第一行就报错了:main(intargc.char**argv){return0;} 11.32 为什么有些ASNI/ISO标准库函数未定义?我明明使用的就是ANSI编译器。 11.33 谁有可以在旧的C程序和ANSIC之间相互转换的工具,或者自动生成原型的工具? 11.34 为什么声称兼容ANSI的编译器不能编译这些代码?我知道这些代码是ANSI的,因为gcc可以编译。 兼容性 11.35 人们好像有些在意实现定义的(implementation-defined)、不确定的(unspecified)和未定义的(undefined)行为的区别。它们的区别到底在哪里? *11.36 一个程序“合法(legal)”、“有效(valid)”或“符合标准的”(conforming)到底是什么意思? 11.37 我很吃惊,ANSI标准竟然有那么多未定义的东西。标准的唯一任务不就是让这些东西标准化吗? 11.38 有人说i=i++的行为是未定义的,但是我刚在一个兼容ANSI的编译器上测试,得到了我希望的结果。它真的是未定义的吗? 第12章 标准输入输出库 基本输入输出 12.1 这样的代码有什么问题?charc;while((c=getchar())!=EOF) 12.2 我有个读取直到EOF的简单程序,但是我如何才能在键盘上输入那个“\EOF”呢?我看stdio.h中定义的EOF是-1,是不是说我该输入-1? 12.3 为什么这些代码把最后一行复制了两遍?while(!feof(infp)){fgets(buf,MAXLINE,infp);fputs(buf,outfp);} 12.4 我用fgets将文件的每行内容读入指针数组。为什么结果所有的行都是最后一行的内容呢? 12.5 我的程序的屏幕提示和中间输出有时没有在屏幕上显示,尤其是当我用管道通过另一个程序输出的时候。为什么? 12.6 我怎样才能不等待回车键而一次输入一个字符? printf格式 12.7 如何在printf的格式串中输出一个'%'字符?我试过\%,但是不行。 12.8 为什么这么写不对?longintn=123456;printf("%d\n",n); 12.9 有人告诉我不能在printf中使用%lf。为什么printf()用%f输出double型,而scanf却用%lf呢? *12.10 对于size_t那样的类型定义,当我不知道它到底是long还是其他类型的时候,我应该使用什么样的printf格式呢? 12.11 如何用printf实现可变的域宽度?就是说,我想在运行时确定宽度而不是使用%8d? 12.12 如何输出在千位上用逗号隔开的数字?货币格式的数字呢? 12.13 为什么scanf("%d",i)调用不行? *12.14 为什么chars[30];scamf("%s",s);不用&也可以?我原以为传给scanf的每个变量都要带&。 12.15 为什么这些代码不行?doubled;scanf("%f",&d); 12.16 为什么这段代码不行?shortints;scanf("%d",&s); 12.17 怎样在scanf格式串中指定可变的宽度? 12.18 怎样从特定格式的数据文件中读取数据?怎样读入10个float而不用使用包含10次%f的奇怪格式?如何将一行的任意多个域读入一个数组中? scanf问题 12.19 我像这样用"%d\n"调用scanf从键盘读取数字:intn;scanf("%d\n",&n);printf("youtyped%d\n",n);好像要多输入一行才返回。为什么? 12.20 我用scanf和%d读取一个数字,然后再用gets()读取字符串,但是编译器好像跳过了gets()调用! 12.21 我发现如果坚持检查返回值以确保用户输入的是我期待的数值,则scanf的使用会安全很多。但有的时候好像会陷入无限循环。为什么? 12.22 为什么大家都说不要使用scanf?那我该用什么来代替呢? 其他stdio函数 12.23 我怎样才知道对于任意的sprintf调用需要多大的目标缓冲区?怎样才能避免sprintf目标缓冲区溢出? 12.24 sprintf的返回值是什么?是int还是char*? 12.25 为什么大家都说不要使用gets? 12.26 我觉得我应该在一长串的printf调用之后检查errno,以确定是否有失败的调用。为什么当我将输出重定向到文件的时候会输出奇怪的“printffailed:Notatypewriter”信息? 12.27 fgetops/fsetops和ftell/fseek之间有什么区别?fgetops和fsetops到底有什么用处? 12.28 如何清除用户的多余输入,以防止在下一个提示符下读入?用fflush(stdin)可以吗? 打开和操作文件 12.29 我写了一个函数用来打开文件:myfopen(char*filename,FILE*fp){fp=fopen(filename,"r");}可我这样调用的时候:FILE*infp;myfopen("filename.dat",infp);,infp指针并没有正确设置。为什么? 12.30 连一个最简单的fopen调用都不成功!这个调用有什么问题?FILE*fp=fopen(filename,'r'); 12.31 为什么我不能用完整路径名打开一个文件?这个调用总是失败:fopen("c:\newdir\file.dat","r"); 12.32 我想用fopen模式"r+"打开一个文件,读出一个字符串,修改之后再写入,从而就地更新一个文件。可是这样不行。为什么? 12.33 如何在文件中间插入或删除一行(一条记录)? 12.34 怎样从打开的流中恢复文件名? 重定向stdin和stdout 12.35 怎样在程序里把stdin或stdout重定向到文件? 12.36 一旦使用freopen之后,怎样才能恢复原来的stdout(或stdin)? 12.37 如何判断标准输入或输出是否经过了重定向,即是否在命令行上使用了“”或“”? 12.38 我想写个像"more"那样的程序。怎样才能在stdin被重定向之后再回到交互键盘? *12.39 怎样同时向两个地方输出,如同时输出到屏幕和文件? “二进制”输入输出 12.40 我希望按字节在内存和文件之间直接读写数字,而不像fprintf和fscanf进行格式化。我该怎么办? 12.41 怎样正确地读取二进制文件?有时看到0x0a和0x0d容易混淆,而且如果数据中包含0x1a的话,我好像会提前遇到EOF。 12.42 我在写一个二进制文件的“过滤器”,但是stdin和stdout却被作为文本流打开了。怎样才能把它们的模式改为二进制? 12.43 文本和二进制输入输出有什么区别? 12.44 如何在数据文件中读写结构? 12.45 怎样编写符合旧的二进制数据格式的代码? 第13章 库函数 字符串函数 13.1 怎样把数字转为字符串(与atoi相反)?有itoa函数吗? 13.2 为什么strncpy不能总在目标串放上终止符'\0'? 13.3 C语言有类似于其他语言中的“substr”(取出子串)的例程吗? 13.4 怎样把一个字符串中所有字符转换成大写或小写? 13.5 为什么有些版本的toupper对大写字符会有奇怪的反应?为什么有的代码在调用toupper前先调用islower? 13.6 怎样将字符串分割成用空白分隔的字段?怎样实现类似main处理argc和argv的过程? 13.7 哪里可以找到处理正则表达式或通配符匹配的代码? 排序 13.8 我想用strcmp作为比较函数,调用qsort对一个字符串数组排序,但是不行。为什么? 13.9 我想用qsort()对一个结构数组排序。我的比较函数接受结构指针,但是编译器认为这个函数不是qsort需要的类型。我要怎样转换这个函数指针才能避免这样的警告? 13.10 怎样对一个链表排序? 13.11 怎样对大于内存容量的数据排序? 日期和时间 13.12 怎样在C程序中取得当前日期或时间? 13.13 我知道库函数localtime可以把time_t转换成结构structtm,而ctime可以把time_t转换成为可打印的字符串。怎样才能进行反向操作,把structtm或一个字符串转换成time_t? 13.14 怎样在日期上加n天?怎样取得两个日期的时间间隔? 随机数 13.15 怎么生成一个随机数? 13.16 怎样获得某一范围内的随机整数? 13.17 每次执行程序,rand都返回相同的数字序列。为什么? 13.18 我需要随机的真/假值,所以我就直接用rand()%2,可是我得到交替的0,1,0,1,0…。为什么? 164 13.19 如何获取根本不重复的随机数? 13.20 怎样产生正态分布或高斯分布的随机数? 13.21 我在移植一个程序,里边调用了一个函数drand48 ,而我的库又没有这个。这是个什么函数? 其他库函数 13.22 exit(status)是否真的跟从main函数返回status等价? 13.23 memcpy和memmove有什么区别? 13.24 我想移植这个旧程序。为什么报出这些“undefinedexternal”错误:index?、rindex?、bcopy?、bcmp?、bzero?? 13.25 我不断得到库函数未定义错误,但是我已经包含了所有用到的头文件了。 13.26 虽然我在连接时明确地指定了正确的函数库,我还是得到库函数未定义错误。 13.27 一个最简单的程序,不过在一个窗口里打印出“Hello,World”,为什么会编译出巨大的可执行代码(数百K)?我该少包含一些头文件吗? 13.28 连接器报告_end未定义代表什么意思? *13.29 我的编译器提示printf未定义!这怎么可能? 第14章 浮点运算 14.1 一个float变量赋值为3.1时,为什么printf输出的值为3.0999999? 14.2 我想计算一些平方根,我把程序简化成这样:main(){printf("%f\h",sqrt(144.));可得到的结果却是疯狂的数字。为什么? 14.3 我想做一些简单的三角函数运算,也包含了math.h,但连接器总是提示sin、cos这样的函数未定义。为什么? 14.4 我的浮点数计算程序表现得很奇怪,在不同的机器上给出了不同的结果。为什么? 14.5 有什么好的方法来检查浮点数在“足够接近”情况下的相等? 14.6 怎样取整? 14.7 为什么C语言不提供乘幂的操作符? 14.8 为什么我机器上的math.h没有预定义常量M_PI? 14.9 怎样将变量置为IEEENaN(“NotaNumber”)或检测变量是否为NaN及其他特殊值? 14.10 如何简洁地处理浮点异常? 14.11 在C语言中如何很好地实现复数? 14.12 我要寻找一些实现以下功能的程序源代码:快速傅立叶变换(FFT)、矩阵算术(乘法、求逆等函数)、复数算术。 14.13 TurboC的程序崩溃,显示错误为“floatingpointformatsnotlinked”(浮点格式未连接)。我还缺点儿什么呢? 第15章 可变参数列表 调用变参函数 15.1 为什么调用printf前必须要包含stdio.h? 15.2 为什么%f可以在printf参数中同时表示float和double?它们难道不是不同类型吗? 15.3 我遇到了一个令人十分受挫的问题,后来发现是这行代码造成的:printf("%d",n);原来n是longint型。难道ANSI的函数原型不就是用来防止这类的参数类型不匹配吗? 15.4 怎样写一个接受可变参数的函数? 15.5 怎样写一个函数,像printf那样接受一个格式串和可变参数,然后再把参数传给printf去完成大部分工作? 15.6 怎样写类似scanf的函数,再把参数传给scanf去完成大部分工作? 15.7 我用的是ANSI前的编译器,没有stdarg.h文件。我该怎么办? 提取可变参数 15.8 怎样知道实际上有多少个参数传入函数? 15.9 为什么编译器不允许我定义一个没有固定参数项的可变参数函数? 15.10 我有个接受float型的变参函数,为什么va_arg(argp,float)却不行? 15.11 为什么va_arg不能得到类型为函数指针的参数? 困难的问题 15.12 怎样实现一个可变参数函数,它把参数再传给另一个可变参数函数? 15.13 怎样调用一个在运行时才构建参数列表的函数? 第16 章奇怪的问题 16.1 为什么这个循环只执行了一次?for(i=start;iend;i++);{printf("%d\n",i);} *16.2 遇到不可理解的不合理语法错误,似乎大段的程序没有编译。 *16.3 为什么过程调用不起作用?编译器似乎直接跳过去了。 16.4 程序在执行之前就崩溃了!(用调试器单步跟踪,在main函数的第一个语句之前就死了。)为什么? 16.5 程序执行正确,但退出时在main函数的最后一个语句之后崩溃了。为什么会这样? 16.6 程序在一台机器上运行完美,但在另一台上却得到怪异的结果。更奇怪的是,增加或去除调试的打印语句,就改变了症状…… 16.7 为什么下面的代码会崩溃?char*p="hello,world!";p[0]='H'; 16.8 我有些代码是用来解析外部结构的,但它却崩溃了,报了“unalignedaccess”(未对齐的访问)错误。这是什么意思? 16.9 “Segmentationviolation”、“Buserror”和“Generalprotectionfault”是什么意思? 第17章 风格 17.1 什么是C最好的代码布局风格? 17.2 如何在源文件中合理分配函数? 17.3 用if(!strcmp(s1,s2))比较两个字符串是否相等是个好风格吗? 17.4 为什么有的人用if(0==x)而不是if(x==0)? 17.5 为什么有些代码在每次调用printf前增加了类型转换(void)? 17.6 既然NULL和0都是空指针常量,我到底该用哪一个? 17.7 是该用TRUE和FALSE这样的符号名称还是直接用1和0来作布尔常量? 17.8 什么是“匈牙利表示法”(HungarianNotation)?是否值得一试? 17.9 哪里可以找到“IndianHillStyleGuide”及其他编码标准? 17.10 有人说goto是邪恶的,永远都不该用它。这是否太极端了? 17.11 人们总是说良好的风格很重要,但当他们使用良好的风格写出清晰易读的程序后,又发现程序的效率似乎降低了。既然效率那么重要,是否可以为了效率牺牲一些风格和可读性呢? 第18章 工具和资源 18.1 能否列一个常用工具列表? 18.2 怎样捕获棘手的malloc问题? 18.3 有什么免费或便宜的编译器可以使用? lint 18.4 刚刚输入完一个程序,但它表现得很奇怪。你能发现有什么错误的地方吗? 18.5 如何关掉lint对每个malloc调用报出的“warning:possiblepointeralignmentproblem”警告消息? 18.6 哪里可以找到兼容ANSI的lint? 18.7 难道ANSI函数原型说明没有使lint过时吗? 资源 18.8 网上有哪些C语言的教程或其他资源? *18.9 哪里可以找到好的源代码实例,以供研究和学习? 18.10 有什么好的学习C语言的书?有哪些高级的书和参考? 18.11 哪里能找到K&R的练习答案? 18.12 哪里能找到NumericalRecipesinC、Plauger的TheStandardCLibrary或Kernighan和Pike的TheUNIXProgrammingEnviroment等书里的源码? 18.13 哪里可以找到标准C函数库的源代码? 18.14 是否有一个在线的C参考指南? 18.15 我需要分析和评估表达式的代码。从哪里可以找到? 18.16 哪里可以找到C的BNF或YACC语法? *18.17 谁有C编译器的测试套件? *18.18 哪里有一些有用的源代码片段和例子的收集? *18.19 我需要执行多精度算术的代码。 18.20 在哪里和怎样取得这些可自由发布的程序? 第19章 系统依赖 键盘和屏幕I/O 19.1 怎样从键盘直接读入字符而不用等回车键?怎样防止字符输入时的回显? 19.2 怎样知道有未读的字符(如果有,有多少)?另外,如何在没有字符的时候不阻塞读入? 19.3 怎样显示一个在原地更新自己的百分比或“旋转棒”的进度指示器? 19.4 怎样清屏?怎样反色输出?怎样把光标移动到指定的x,y位置? 19.5 怎样读入方向键、功能键? 其他I/O 19.6 怎样读入鼠标输入? 19.7 怎样做串口(“comm”)的输入输出? 19.8 怎样直接输出到打印机? 19.9 怎样发送转义字符序列控制终端或其他设备? 19.10 怎样做图形? *19.11 怎样显示GIF和JPEG图像? 文件和目录 19.12 怎样检验一个文件是否存在?如果请求的输入文件不存在,我希望向用户提出警告。 19.13 怎样在读入文件前,知道文件大小? *19.14 怎样得到文件的修改日期和时间? 19.15 怎样原地缩短一个文件而不用清除或重写? 19.16 怎样在文件中插入或删除一行(或一条记录)? 19.17 怎样从一个打开的流或文件描述符得到文件名? 19.18 怎样删除一个文件? *19.19 怎样复制文件? 19.20 为什么用了详尽的路径还不能打开文件?下面的代码会返回错误。Fopen("c:\newdir\file.dat","r") *19.21 fopen不让我打开文件"$HOME/.profile"和"~~/.myrcfile"。 *19.22 怎样制止MS-DOS下令人恐怖的“Abort,Retry,Ignore?”信息? 19.23 遇到“Toomanyopenfiles(打开文件太多)”的错误,怎样增加同时打开文件的允许数目? 19.24 如何得到磁盘的可用空间大小? 19.25 怎样在C语言中读入目录? 19.26 如何创建目录?如何删除目录(及其内容)? 访问原始内存 19.27 怎样找出系统还有多少内存可用? 19.28 怎样分配大于64K的数组或结构? 19.29 错误信息“DGROUPdataallocationexceeds64K(DGROUP数据分配内存超过64K)”什么意思?我应该怎么做?我以为使用了大内存模型,就可以使用大于64K的数据! 19.30 怎样访问位于某特定地址的内存(内存映射的设备或图形显示内存)? 19.31 如何访问机器地址0处的中断向量?如果将指针设为0,编译器可能把它转成一个非零的内部空指针值。 “系统”命令 19.32 怎样在一个C程序中调用另一个程序(独立可执行的程序或系统命令)? 19.33 如果运行时才知道要执行的命令的参数(文件名等),应该如何调用system? 19.34 在MS-DOS上如何得到system返回的准确错误状态? 19.35 怎样调用另一个程序或命令,然后获取它的输出? 进程环境 19.36 怎样才能发现程序自己的执行文件的全路径? 19.37 怎样找出和执行文件在同一目录的配置文件? 19.38 进程如何改变它的调用者的环境变量? 19.39 如何打开命令行给出的文件并解析选项? 19.40 exit(status)是否真的和从main函数返回同样的status等价? 19.41 怎样读入一个对象文件并跳跃到其中的函数? 其他系统相关的操作 19.42 怎样以小于1秒的精度延时或计算用户响应时间? 19.43 怎样捕获或忽略control-C这样的键盘中断? 19.44 怎样简洁地处理浮点异常? 19.45 怎样使用socket?如何联网?如何写客户/服务器程序? *19.46 怎样调用BIOS函数?如何写ISR?如何创建TSR? *19.47 什么是“near”和“far”指针? 回顾 19.48 我不能使用这些非标准、依赖系统的函数,程序需要兼容ANSI! 19.49 为什么这些内容没有在C语言中进行标准化?任何现实程序都会用到这些东西。 第20章 杂项 20.1 怎样从函数返回多个值? 20.2 用什么数据结构存储文本行最好?我开始用固定大小的char型数组的数组,但是有很多局限。 20.3 怎样打开命令行提到的文件并处理参数? 20.4 如何正确地使用errno? 20.5 怎样写数据文件,使之可以在不同字大小、字节顺序或浮点格式的机器上读入? 20.6 怎样用char*指针指向的函数名调用函数? 位和字节 20.7 如何操作各个位? 20.8 怎样实现位数组或集合? 234 20.9 怎样判断机器的字节顺序是高字节在前还是低字节在前? *20.10 怎样调换字节? 20.11 怎样将整数转换到二进制或十六进制? 20.12 可以使用二进制常数(类似0b101010这样的东西)吗?printf有二进制的格式说明符吗? 效率 20.13 用什么方法计算整数中为1的位的个数最高效? 20.14 怎样提高程序的效率? 20.15 指针真的比数组快吗?函数调用会拖慢程序多少?++i比i=i+1快吗? 20.16 用移位操作符替换乘法和除法是否有价值? *20.17 人们说编译器优化得很好,我们不再需要为速度而写汇编了,但我的编译器连用移位代替i/=2都做不到。 *20.18 怎样不用临时变量而交换两个值? switch语句 20.19 switch语句和if/else链哪个更高效? 20.20 是否有根据字符串进行条件切换的方法? 20.21 是否有使用非常量case行标的方法(如范围或任意的表达式)? 各种语言功能 20.22 return语句外层的括号是否真的可选择? 20.23 为什么C语言的注释不能嵌套?怎样注释掉含有注释的代码?引号包含的字符串内的注释是否合法? 20.24 为什么C语言的操作符不设计得更全面一些?好像还缺了一些^^、&&=和-=这样的操作符。 *20.25 C语言有循环移位操作符吗? *20.26 C是个伟大的语言还是别的什么东西?哪个其他语言可以写出像a+++++b这样的代码? 20.27 如果赋值操作符是:=,是不是就不容易意外地写出if(a=b)了? 20.28 C语言有和Pascal的with等价的语句吗? 20.29 为什么C语言没有嵌套函数? *20.30 assert是什么?如何使用? 其他语言 20.31 怎样从C中调用FORTRAN(C++、BASIC、Pascal、Ada、LISP)的函数?反之如何? 20.32 有什么程序可以将Pascal或FORTRAN(或LISP、Ada、awk、“老”C)程序转化为C程序? 20.33 C++是C的超集吗?可以用C++编译器来编译C代码吗? 20.34 我需要用到“近似”的strcmp例程,比较两个字符串的近似度,并不需要完全一样。有什么好办法? 20.35 什么是散列法? 20.36 如何生成正态或高斯分布的随机数? 20.37 如何知道某个日期是星期几? 20.38 (year%4==0)是否足以判断闰年?2000年是闰年吗? 20.39 为什么tm结构中的tm_sec的范围是0到61,暗示一分钟有62秒? 琐事 20.40 一个难题:怎样写一个输出自己源代码的程序? 20.41 什么是“达夫设备”(Duff’sDevice)? 20.42 下届国际C语言混乱代码竞赛(InternationalObfuscatedCCodeContest,IOCCC)什么时候进行?哪里可以找到当前和以前的获胜代码? 20.43 K&R1提到的关键字entry是什么? 20.44 C的名字从何而来? 20.45 “char”如何发音? *20.46 “lvalue”和“rvalue”代表什么意思? 20.47 哪里可以获得本书的在线版? 术语表 参考文献

64,701

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧