`
puppy1226
  • 浏览: 698 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

C++ Primer Study 1

阅读更多

2010-7-10: C++ Primer 4th Edition Chapter 11 Generic Algorithm

Page 349 – Page 372 Main Content: Iterator

Practice with Sample Program

(IDE CodeBlocks Compiler GCC)

#include <iostream>
#include<vector>
#include<iterator>
#include<algorithm>
using namespace std;
int main(){
    cout << "Please input the number for sorting:" << endl;
    //define inputstream iterator from cin 
    istream_iterator<int> cin_it(cin);
    //define iterator to label the end of inputstream
    istream_iterator<int> end_of_stream;
    //initialize vec from the standard input
    vector<int> vec(cin_it,end_of_stream);
    vector<int>::iterator it_before = vec.begin();
    sort(vec.begin(),vec.end());
    vector<int>::iterator it_after = vec.begin();
    //write ints to cout using " " as a delimiter
    ostream_iterator<int> output(cout, " ");
    //store the unique value into outputstream
    unique_copy(vec.begin(),vec.end(),output);
    return 0;
}

 Debug 过程中遇到了 "cout was not delared in the scope" 等,由于没有使用声明 using namespace std,而导致的使用C++标准库时出现的未定义问题。添加using namespace std 后解决。

 

附: using namespace std 详解

一 :
<iostream>和<iostream.h>是不一样,前者没有后缀,实际上,在你的编译器include文件夹里面可以看到,二者是两个文件,打开文件就会发现,里面的代码是不一样的。

后缀为.h的头文件c++标准已经明确提出不支持了,早些的实现将标准库功能定义在全局空间里,声明在带.h后缀的头文件里,c++标准为了和C区别开,也为了正确使用命名空间,规定头文件不使用后缀.h。

因此,当使用<iostream.h>时,相当于在c中调用库函数,使用的是全局命名空间,也就是早期的c++实现;当使用<iostream>的时候,该头文件没有定义全局命名空间,必须使用namespace std;这样才能正确使用cout。

二:
所谓namespace,是指标识符的各种可见范围。

C++标准程序库中的所有标识符都被定义于一个名为std的namespace中。

由于namespace的概念,使用C++标准程序库的任何标识符时,可以有三种选择:

1、直接指定标识符。例如std::ostream而不是ostream。完整语句如下:

std::cout << std::hex << 3.4 << std::endl;

2、使用using关键字。

using std::cout;
using std::endl;

以上程序可以写成

cout << std::hex << 3.4 << endl;

3、最方便的就是使用using namespace std;

例如:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
这样命名空间std内定义的所有标识符都有效(曝光)。就好像它们被声明为全局变量一样。那么以上语句可以如下写:

cout << hex << 3.4 << endl;

因为标准库非常的庞大,所程序员在选择的类的名称或函数名时就很有可能和标准库中的某个名字相同。所以为了避免这种情况所造成的名字冲突,就把标准库中的一切都被放在名字空间std中。但这又会带来了一个新问题。无数原有的C++代码都依赖于使用了多年的伪标准库中的功能,他们都是在全局空间下的。 
所以就有了<iostream.h>和<iostream>等等这样的头文件,一个是为了兼容以前的C++代码,一个是为了支持新的标准。
命名空间std封装的是标准程序库的名称,标准程序库为了和以前的头文件区别,一般不加".h"

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics