[CPP] STL and namespace

Namespace

  • namespaces are used to avoid name conflicts
  • To put code in a namespace use:
    namespace <NamespaceName>
     {
         <put code for classes or functions here>
     }
    
  • Can use scoping to specify a namespace to ‘look in’:
  • < namespace >::< class >::< function > or < namespace>::< globalfunction>
  • you can avoid keeping saying :: by “using namespace
  • The standard class library is in the std namespace

The scoping operator

Left of scoping operator is
  • blank(to access a global variable/function)
  • class name(to access member of that class)
  • namespace name(to use that namespace)
    enter image description here
if there is just :: but nothing on the left, it means global
enter image description here
On the right, there are three different main(), only 2 and 3 will compile successfully because:
  • The first main() doesn’t clarify which MyPrintFunction1() it calls, so it will be ambiguous.
  • The second main() means the global function which is on the left bottom
  • The third main() means the function from namespace cpp

Standard class library classes

String

string has been covered in the previous blog
note: obtain a const char * for the string–> c_str()

streams for input/output

Three standard streams exist already
  • istream cin; (matches stdin)
  • ostream cout; (matches stdout)
  • ostream cerr; (matches stderr)

File access using streams

  • ifstream object -open the file for input
  • ofstream object -open the file for output
  • fstream object -specify what to open file for
  • use the << and >> operators to read/write

File output example

enter image description here
The file will be like:
Hello File
75

File input example

enter image description here
It is based on the file above, it will read all the file content, output will be “Hello”, str will be “File”, x will be 75

strstream

enter image description here
But strstream will stop reading in when it encounter to a “space”, so C++ standard said it is not recommended to use, we should use stringstream

Standard Template Library

A larger library of template classes and algorithms.
enter image description here
We have covered some important STL like vector before.

评论

此博客中的热门博文

[MLE] W2 Multivariate linear regression

[MLE] W1 Introduction

[AIM] MetaHeuristics