C + + Primer The first part of the basic language _c language

Source: Internet
Author: User
Tags bitset flush function definition gcd lowercase

1th Chapter Quick Start

1, introduce the meaning of main function and its basic structure, return statement. Compile and execute programs under different platforms.
2, two classes Isrteam with Otream and their instance objects cin,cout,cerr,clog. The basic input and output of the program are explained. "<<" and ">>" as operators, the left operator is a iostream object, the right operator is a variable. The return value is still a iostream object, so the input or output can be written cout<< "a=" <<a<<endl attached.
The two annotation styles in 3,c++ and the problems needing attention.
4, control result: loop (while with for), select (If...else ...) )。 Introduces an example that computes all integers between two numbers.
The most important feature of 5,c++: Class. Describes some of the operations defined on the class, simply introducing member functions, using the "." To invoke the member function.
6, the book begins with the introduction of a bookstore bibliography problem, with a complete program that further illustrates some of the basic elements of C + + programs. Of course, Scales_item does not have specific implementation code.

2nd Chapter variables and basic types

1, when performing arithmetic operations, the choice of data type: Short is generally rarely used, prone to cross borders. Char types are sometimes treated as signed in some implementations and sometimes as unsigned, so it is advisable to use char only to represent characters. So in most cases using int is fine, on many machines int is stored in 4 bytes, enough to meet most of the computational requirements. The choice of floating-point types is simple, with a double type with little or no error, and may be less expensive than the float calculation.

2, literal constants. Only built-in types exist literal values. Wide-character type wchar_t, in fact, the literal character constants the amount preceded by a "L", such as wchar_t c=l ' a '; a multiline string can be connected with ' \ ', but after \ No spaces or tabs can be followed, and no spaces or tabs can precede the next line of string literals.

3, introduced the concept of variables, the naming of variable names specification: 1 variable name is generally used in lowercase letters; 2) identifiers best meaningful; 3 multiple words are underlined or embedded in the first letter of the word. In addition, identifiers are not named with two consecutive underscores or underscores + uppercase letters.

4, define the object (variable definition). Variables can be initialized when they are defined, you can choose to initialize them (do not understand to assign values), or you can choose to initialize directly.

Copy Code code as follows:

int ival (1024); Direct-initialization
int ival = 1024; Copy-intialization

5, the difference between the definition and the declaration, attention to the use of extern.

The use of the 6,const qualifier. A const-defined variable cannot be modified, so it must be initialized at the time of definition. If you want to use the const variable in multiple files, you must declare it as an external variable when you define it, that is, extern.

7, introduced with the Const.

1 A cosnt reference can only be bound to an object of the same type as the reference.

2) A const reference can be bound to a different but related type of object or bound to a right value.

8, enum type enum.

9,struct differs from class when creating classes: The default access level for struct is public, and class is private.

10, the use and writing of C + + language header files, and the use of defining preprocessor variables to avoid duplicate inclusion of header files.

3rd Chapter Standard library type

1, the using declaration of the namespace

Using std::string

2, standard library string type

Standard library String type. String and string literals are not of the same type, note the constructors of several strings.

When the string type is read with CIN, all whitespace characters at the beginning are read and ignored until a blank character is encountered again, and the read is terminated.

Getline can read a row in the input stream, but does not include line breaks.

When a string object is compared, the lowercase letters are larger than uppercase letters, that is, uppercase letters are in the front.

The subscript for a string object starts at 0 to S.size ()-1.

3, standard library vector type

C + + programmers are accustomed to priority use! = instead of < to write circular judgment conditions. For (String::size_type i=0 i!= s.size (); i++)

When the C + + compiler encounters an inline function, it extends the corresponding code directly, rather than the actual function call, so a small library function such as size can be invoked in a loop for a very small price.

4. Introduction to Iterators

Each container defines the begin and end functions, and begin returns the first element of the container, and the End function returns the next of the vector's terminal element, often called an out of terminal iterator, indicating that it points to an element that does not exist. If the vector is empty, the iterator returned by begin is the same as the iterator returned by end. End returns an iterator that is actually a "sentry".

Note the difference:

Vector<int>::const_iterator//An iterator that cannot write elements

Const Vector<int>::iterator//A iterator whose value cannot change

5,bitset type

Several Bitset constructors:

Bitset<n> b;

Bitset<n> b (U); U is a number usigned long, which will be converted into binary numbers

Bitset<n> b (s); B is a copy of the string object s containing a bit string

Bitset<n> b (s,pos,n); B is an n-digit copy of S in which the POS starts from position

4th chapter Arrays and pointers

1, array

None of the elements are referenced arrays, and the types defined in the array can be built-in data types or class types or any compound type (except for references).

The dimensions of an array can only be used for constant values that can be known at compile time.   const int Arsize=num; int ar[arsize]; This is not possible because the NUM variable is not calculated at run time.

If the array is not explicitly initialized, is initialized like a normal variable: 1 The function is defined in the body, then initialized to 0;2) in the function body, its elements are not initialized, 3 regardless of where the array is, if its element is a class type, the default constructor of the class is called automatically. If the class does not have a default constructor, you must provide an explicit initialization for the elements of the array.

A vector object cannot be initialized directly with the number of the same type. Suppose to have the following array: const int ar_size=5; Ar[ar_size]={0,1,2,3,4}>

Vector<int> Ivec (AR); Error

Vector<int> Ivec (ar,ar+ar_size); Ok

2, introduction of the pointer

Do not allow 0 of int to be assigned to pointers, but you can assign a const-modified 0 to a pointer

cosnt int c_ival=0; int *p=c_ival;

C + + provides a special type of pointer void*,void* that supports only a limited number of operations: 1 is compared to another pointer, 2 passes a void* pointer to a function or returns a void* pointer from a function, and assigns a value to another void* pointer. Using the void* pointer is not allowed to manipulate the object it points to.

ptrdiff_t is the type defined in the standard library to hold the result of subtraction between pointers to the same type.

Const int* PTR; PTR can point to his variable, but you cannot use PTR to change the value of the variable it points to until you change the PTR.

int* const PTR; PTR cannot point to other variables, but you can change the value of the variable that PTR points to.

Attention:

typedef string *pstring;

Const Pstring CStr;

The CStr above is a const pointer that points to a variable of type string. pstring Const CSTR is the same.

3,c style string

Each program occupies an available memory space, which is used to store dynamically allocated objects, which are called free storage areas or heaps of programs.

An array that is dynamically allocated cannot use an initialization list like an array, and can only be initialized to the default value of an element type. int* ar=new int[10] (); The trailing empty parentheses allow the array elements to be initialized to 0.

When freeing free storage with Delete, if you are releasing an array, don't forget []. delete [] ar;

Note the member function c_str () of a String object can return the first pointer to a string. But you should add a const. Const char* STR=S.C_STR ();

int* Ip[4]: An array of pointers to int.

int (*IP) [4]: A pointer to an array of pointer 4 elements.

The 5th chapter of expression

1, the difference between i++ and ++i

The post operator needs to first save the original value, then i+1, then return the original value, and the front operator, just add 1 to the original value, and then return. So ++i is more efficient than i++, of course if I is an int type, the compiler optimizes i++, but not if it is another class type or pointer.

2, note that the dereference operator and the + + operator priority, in the actual code for simplicity often write * (i++) as *i++. Because + + has a higher precedence than the dereference operator.

3, when using the conditional operator, try to avoid writing a depth-nested conditional operator. In addition, the precedence of the conditional operator is very low, and the parentheses are used in the expression, such as:cout<< (I<J?I:J);

4, about the sizeof operator. The result of the sizeof is a compile-time constant, noting the value of the following code:

Copy Code code as follows:

int a[10];
int* p = A;
int n1 = sizeof (a)/sizeof (*A); n1=10
int n2 = sizeof (p)/sizeof (*P); N2=1

5, when you evaluate a compound expression, pay special attention to the precedence and binding of the operators. In particular,! = = = = Priority is less than <=,>= and other relational operators.

6, when using new for dynamic memory allocation, there are several noteworthy points to note:

1 dynamically created objects can be initialized with parentheses, such as:

Copy Code code as follows:

int* p = new int ();//initialized to 0
int* q = new int (1024);//Initialize to 1024

2 Delete 0 pointers can be deleted, and delete is allocated to the memory area, and did not delete the pointer variable p,p still point to the original address, but the original memory does not exist. When P is called a dangling pointer, the p should be set to 0.

3 Avoid the use of the same memory space two times delete. 、

6th Chapter Statement

1, when using block statements, note that variable scopes defined within a block statement are within a block area only. In particular, variables that are initialized or defined in a control statement, such as an if or a for statement, have only the scope of the block area.

The use of 2,switch statements. The case label must be a shape constant expression and not allow the variable to be defined within the switch statement if there are cases or default statements underneath it, because in some situations, the execution variable defines the following case branch in cases where there are no instances where the definition of the variable is executed. Unless the variable is defined within the code block.

3, in the For loop, if there is a continue statement, the statement that follows the continue is skipped, but the change statement for the counter in the For statement is not skipped.

4, you can use the preprocessor for debugging.

Copy Code code as follows:

#ifndef Ndebug
cout << "some useful information!";
#endif//! Ndebug

You can decide whether to print those debugging information by adding parameters at compile time.

7th Chapter function

1, a function can be seen as a programmer's own definition of the operator, the same function as the operator can be overloaded.

2, the following is the function of finding gcd by the Euclidean method, which illustrates the basic structure of the function definition.

Copy Code code as follows:

int gcd (int v1, int v2)
{
Seeking GCD by Euclidean method
while (v2)
{
int temp = v2;
v2 = V1%v2;
V1 = temp;
}
return v1;
}

5, a function that does not return a value (the return value is void) is generally not allowed to return statements, but returns a function expression with return value of void.

Copy Code code as follows:

void Fun1 ()
{
void Fun2 ();
return fun2 ();
}

6, the function allows the default argument to be provided, which, when invoked, can be omitted while the program uses the default value. You should typically specify a default argument in a function declaration and place the declaration in the appropriate header file.

7, the variables defined in the function body have the scope of the block area, and can be divided into two kinds of automatic objects, such as: formal parameters. This type of object is created every time the function is called, and is destroyed when the function is done. Another object is a static local object that is revoked only at the end of the program. Otherwise it is kept in memory.

8, for a function that often needs to be called and short, it can be set to an inline function, which, at compile time, expands the function at the function call and makes code substitution. This avoids the overhead in the function call. Defining an inline function is to add inline before the function definition. It is generally necessary to place the inline function in the header file.

9, in the member function of a class, there is a class of functions followed by the Const qualifier, which is used to describe a constant member function that can only read data members that cannot alter an object when it is used.

10, do not write the this pointer in the parameter list of the member function.

11, when you define a class, if you do not define a default constructor, the compiler creates a composite default constructor for the class. This function initializes the member variables of the class to the corresponding variable type initialization method: The class type will invoke the default constructor of the class, and the built-in type depends on whether the environment is global or static local or local. A synthesized default constructor applies only to classes that contain members of a class type.

12, a function cannot implement overloads based solely on different return types.

13,const issues to note in function overloading:

Copy Code code as follows:

void fun (int num);
void fun (const int num); Repeat statement

void fun (int& num);
void Fun (const int& num); Can overload

void fun (int* num);
void Fun (const int* num); Can overload

14, locally declared functions will mask overloaded functions that will be globally defined.

Copy Code code as follows:

void Fun (int x, int y = 1);
int main ()
{
void fun (double x);
Fun (2,4); Error
return exit_success;
}

15, pointing to the function pointer

The function pointer points to a function rather than to an object. BOOL (*PF) (int,int*); Where PF is a function pointer, the type of which is "a pointer to a function that returns the type bool with an int and a int* parameter."

1 You can use a typedef to give a simple definition of the pointer to the specified function:

Copy Code code as follows:

typedef BOOL (*CMPFCN) (int,int*);
CMPFCN F1, F2;

The code above defines a type of pointer function and provides an alias with a typedef. Both F1 and F2 are pointers of this type.

2 initialization and assignment of pointers to functions

When a function name is not called, it is interpreted as a pointer to a function and can be assigned to a pointer of the same type.

The pointer to the function is assigned a value of 0, indicating that no function is pointed to.

When you assign a pointer to a function, there is no type of conversion.

3 Call function by pointer

You do not have to dereference symbols, such as: F1 (1,2), (*F1) (1,2).

4 A pointer to a function can be used as a formal parameter of a function:

Copy Code code as follows:

void Ivectsort (Vector<int>::iterator, Vector<int>::iterator, BOOL (*) (int,int));
void Ivectsort (Vector<int>::iterator, vector<int>::iterator, bool (int, int));

The 3rd parameter in the declaration of the above two functions is one pointing to the function pointer type, and the 3rd parameter of the following type is a function type, which is automatically converted to a pointer type.

5 The function type can be used as the formal parameter of a function, but it cannot be the return type of a function.

6 The type must be identical when the pointer to the function points to an overloaded function.

8th Chapter Standard IO Library

1, the standard library type does not allow replication and assignment operations. Because only element types that support replication can be stored in vectors, a stream object cannot be stored in a vector or container, and a function's shape-participating return type cannot be a stream type, and must be passed or returned to a reference or pointer to that object if needed. In general, if you want to pass an IO object to read and write to it, you can pass the stream object in a non-const reference. Reading and writing to an IO object changes its state, so it must be non const.

2, each IO object manages a buffer, and there are several ways to flush the buffer (write the buffer contents to the device).

1 Refresh of output buffer: Flush flush stream without adding any characters; ends this operator inserts a null character in the buffer and then refreshes it. Endl line wrap and refresh.

2 The UNITBUF operator:cout<<unitbuf<< "the" "The" "The" "The" "The" "second" <<nounitbuf;nounitbuf operator returns the stream to normal, The system-managed buffer Refresh method.

3 The buffer will not be flushed when the program crashes. This requires special attention when debugging a crashed program.

4 The TIE function can be used to bundle IStream with Ostream, and when any IO operation is used, the buffer associated with the argument is brushed.

3, note that the state of the file stream is cleared, the following program reads the name of the file from a vector and processes the contents of each file, and if the starting stream is defined outside the loop, the state of the file stream needs to be purged at the end of the loop.

Copy Code code as follows:

Ifstream input; Input is defined outside the loop
Vector < String::const_iterator it = Files.begin ();
while (it!= files.end ())
{
Input.open (It->c_str ());
if (!input)
Break
while (input >> s)
Process (s);
Input.close ();
Input.clear (); Clears the state of a file stream
++it;
}

In the above program, every time you read the file, you will end up with a file terminator or some other error, where input is in the wrong state. If the state of the clear elimination stream is not invoked before the stream is closed, any input operations made on the input will fail.

4,stringstream is derived from iostream and provides the ability to read and write strings. You can convert a string into a stream for input or output. There are two main common uses for this class:

1 Make a string of variable values in a certain format. Suppose that in a loop, we want to save the intermediate data to the hard disk, then we need the filename, and we need to write the looping index to the filename to avoid duplication of the file name.

Copy Code code as follows:

Ostringstream filename;
string prefix = "File_";
string suffix = ". jpg";
for (int i = 0; i < i++)
{
FileName << prefix << i << suffix;
}

2) A string of formatted strings, parsed into some basic type data by format. For example, you need to extract the string from the contents of a row of log files and integers separately:

Copy Code code as follows:

String logcontent = "20140225 c++primer 42";
Istringstream input (Logcontent.c_str ());
string dump;
int price;
Input >> dump >> dump >> price;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.