C ++ Basics

Source: Internet
Author: User
Tags bit set bitset control characters printable characters

1. constructor Initialization
Animal: Animal (): aget (1), maxlevel (30)
{
}
2. Private Data members in the user metadata class are not allowed unless they are friends.
Friend void fun (Animal & );
Void fun (Animal &)
{
Cout <A. Name <Endl;
}
3. If the parameter is a pointer and only used for input, you should add const before the type to prevent the pointer from being accidentally modified in the function body.
For example:
Void stringcopy (char * strdestination, const char * strsource );
If the input parameter is passed as a value, you should use"Const &"In this way, you can save the construction and analysis process of the temporary object, thus improving the efficiency.

4. the return value of the function is an object.

If the return value of a function is an object, in some cases, replacing "value transfer" with "reference transfer" can improve the efficiency. In some cases, you can only use "value transfer" instead of "reference transfer". Otherwise, an error occurs.
For example:
Class string
{...
// Value assignment function
String & operate = (const string & other );
// Add function. If there is no friend modifier, only one parameter on the right is allowed.
Friend string operate + (const string & S1, const string & S2 );
PRIVATE:
Char * m_data;
}

The implementation of the string value assignment function operate = is as follows:
String & string: operate = (const string & other)
{
If (this = & other)
Return * this;
Delete m_data;
M_data = new char [strlen (other. Data) + 1];
Strcpy (m_data, other. data );
Return * This; // The returned result is a reference of * This, without the need to copy the process.
}

For the value assignment function, the string object should be returned using the "reference transfer" method. If the "value transfer" method is used, although the function is still correct, but because the return statement needs to copy * this to the external storage unit that saves the returned value, unnecessary overhead is added, this reduces the efficiency of the value assignment function. For example:
String A, B, C;
...
A = B; // If "value transfer" is used, a * This copy will be generated.
A = B = C; // If "value transfer" is used, two * This copies will be generated.

The implementation of the string addition function operate + is as follows:
String operate + (const string & S1, const string & S2)
{
String temp;
Delete temp. Data; // temp. Data is a string containing only '\ 0'
Temp. Data = new char [strlen (s1.data) + strlen (s2.data) + 1];
Strcpy (temp. Data, s1.data );
Strcat (temp. Data, s2.data );
Return temp;
}

For Addition functions, the string object should be returned using the "value transfer" method. If "reference transfer" is used, the return value of the function is a "Reference" pointing to the local object temp ". Because temp is automatically destroyed at the end of the function, the returned "Reference" is invalid. For example:
C = A + B;
At this time, A + B does not return the expected value, and C does not get anything, causing hidden risks.

5. Comparison between reference and pointer

 

References are a concept in C ++. Beginners can easily confuse references with pointers. Click Program N is a reference of M, and M is a referent ).
Int m;
Int & n = m;
N is equivalent to M alias (nickname). Any operation on N is an operation on M. For example, someone named Wang xiaomao, whose nickname is "San Mao ". The reason for saying "three hairs" is actually to say three things to Wang xiaomao. Therefore, n is neither a copy of M nor a pointer to M. In fact, n is m itself.
Some referenced rules are as follows:
(1) The reference must be initialized at the same time (the pointer can be initialized at any time ).
(2) there cannot be a null reference, and the reference must be associated with a valid storage unit (the pointer can be null ).
(3) once the reference is initialized, the reference relationship cannot be changed (the pointer can change the object at any time ).
In the following example, K is initialized as a reference of I. Statement K = J cannot be changed to a reference of J, but the value of K is changed to 6. Since K is an I reference, the I value is also changed to 6.
Int I = 5;
Int J = 6;
Int & K = I;
K = J; // The values of K and I are changed to 6;
The above program looks like playing a text game and does not reflect the value of reference. The main function of the reference is to pass the parameters and return values of the function. In C ++, function parameters and return values are transmitted in three ways: value transfer, pointer transfer, and reference transfer.
The following is a sample program for "value transfer. Since X in the func1 function is a copy of the external variable N, changing the value of X does not affect N, so the value of N is still 0.
Void func1 (int x)
{
X = x + 10;
}
...
Int n = 0;
Func1 (N );
Cout <"n =" <n <Endl; // n = 0

The following is an example program for "pointer passing. Since X in the func2 function is a pointer to the external variable N, changing the content of this pointer will change the value of N, so the value of N is 10.
Void func2 (int * X)
{
(* X) = (* x) + 10;
}
...
Int n = 0;
Func2 (& N );
Cout <"n =" <n <Endl; // n = 10

The following is a sample program for "reference transfer. Since X in the func3 function is a reference of the external variable n, x and n are the same thing, changing X is equal to changing N, so the value of N is 10.
Void func3 (Int & X)
{
X = x + 10;
}
...
Int n = 0;
Func3 (N );
Cout <"n =" <n <Endl; // n = 10

Comparing the above three examples, we will find that the nature of "Reference transfer" is like "pointer transfer", and the writing method is like "value transfer ". In fact, all the things that can be done by "reference" can also be done by "pointer". Why do we need to "reference" this?
The answer is "Use appropriate tools for proper work ".
Pointers can operate on the memory without any constraints. Although pointers are powerful, they are very dangerous. Like a knife, which can be used to cut trees, cut paper, manicure, and cut hair. Who dares to use it like this?
If you only need to borrow the "alias" of an object, use "Reference" instead of "Pointer" to avoid exceptions. For example, a person needs a proof that the seal was originally printed on the document. If he handed over the key to the seal, he would have obtained the right he did not have.

 

6. & true when both sides are true | true when both sides are true.
False is 0 in the arithmetic expression, and true is 1.
7. arithmetic operation Priority
Logical operator no. Not
Arithmetic Operators (*,/, %)
Arithmetic Operators (+ ,-)
Relative join operator (= ,! =)
Logical operator number and
Logical operator number or
Value assignment operator
8. Continue terminate the current iteration of the loop
String word;
Const int min_size = 4;
While (CIN> word)
{
If (word. Size () <min_size)
// End the iteration
Continue;
// When the program runs here, the input length is greater than or equal to min_size.
Process_text (Word );
}
9. Const int seq_size = 18;
# Include <vector>
Vector <int> pell_seq (seq_size) // pell_ SQL is defined as a vector object, which can store 18 int elements. The initial value of each element is 0.
For (int ix = 2; ix <seq_size; ++ IX)
Pell_ SQL [ix] = pell_seq [ix-2] + 2 * pell_seq [ix-1];
// Vector Initialization
Vector <int> elem_seq (SQL _size );
Elem_ SQL [0] = 1;
Elem_ SQL [1] = 2;
Or:
Use an initialized array as the initial value of the vector.

Int elem_vals [seq_size] = {
1, 2, 3
};
Vector <int> elem_seq (elem_vals, elem_vals + seq_size );

 

9. Initialization:
Int ival (1024) Direct Initialization is more flexible and efficient
Int ival = 1024 copy Initialization
10. extern
Extern int I; the Declaration is not a definition.
Extern int I = 65535; defined
Variables in the program can be declared multiple times, but can only be defined once.

11:
reference:
the reference must be initialized with an object of the same type as the reference.
int ival = 1024;
Int & refval = ival; // OK: refval refers to ival
Int & refval2; // error: A reference must be initialized
Int & refval3 = 10; // error: initalizer must be an object
const reference: Reference to the const object:
const int ival = 1024;
const Int & refval = ival; // OK: both reference and object are const;
Int & ival = ival; // error: Non C Onst reference to a const object;
you can read but cannot modify refval;
a const reference can be initialized to an object of different types or be initialized to the right.
int I = 42;
const Int & R = 42; // legar for const references only
cont Int & Re = R + I;

Double dval = 3.14;
Const Int & rI = dval;
The compiler converts it to the following format:
Int temp = dval;
Const Int & rI = dval;

// Non-const references can only be bound to objects of the same type as the reference.
Const reference can be bound to different but related types of objects or to the right value.

12: Enumeration

The enumerated Member values can be unique:
Enum points {point2d = 2, point2w, point3d = 3, point3w };
Point2w is initialized by default. It is 3. point3w is 4.
The initialization or assignment of enumeration objects can only be performed by its enumerated members or other objects of the same Enumeration type.
Points pt3d = point3d; // OK: point3d is a points enumerator;
Points pt2w = 3; // error: pt2w initialized whit int
Pt2w = polygon; // error: polygon is not a points enumerator
Pt2w = pt3d; // OK: both are objects of points Enum type
It is invalid to assign 3 to the points object, even if 3 is associated with a points enumeration member.

13: class type
The only difference between defining a class with the class and struct keywords lies in the default access level. By default,
The struct member is public, and the class member is private;

14: the header file is used for declaration rather than definition.
Extern int ival = 10; // initializer, so it's a definition
Double fica_rate; // No extern, so it's a definition
Because the header file is contained in multiple source files, it should not contain the definition of variables or functions.

15: Avoid Multiple inclusion

# Ifndef xxx_h
# Define xxx_h
# Endif

16: String

Definition and initialization of a string object
String S1; // default constructor. S1 is an empty string.
String S2 (S1); // initialize S2 as a copy of S1.
String S3 ("value"); // initialize S3 as a copy of the string literal value
String S4 (n, 'C'); // initializes S4 into N copies of the character 'C'
Warning the string literal value is not of the same type as the string type in the standard library.

* Link to the string literal value:
When the string object and the string literal value are joined together, the plus and minus operands of the + operator must be of the string type at least. String S1 = "hello ";
String S2 = "world ";
String S3 = S1 + ","; // OK: adding a string and literal
String S4 = "hello" + ","; // error: no string operand
String S5 = S1 + "," + "world"; // OK: Each + has string operand
String S6 = "hello" + "," + S2; // error: cant add string literals;
* Get characters from the string object
String STR ("some string ");
For (string: size_type IX = 0; ix! = Str. Size (); ++ IX)
Cout <STR [ix] <Endl;
* The subscript operation can be used as the left value.
For (string: size_type IX = 0; ix! = Str. Size (); ++ IX)
STR [ix] = '*';
* Character Processing in the header file of cctype
Isalnum (c) letters or numbers
Isalpha (c) Letters
Iscntrl (c) control characters
Isdigit (c) Numbers
Isgraph (c) is not a space, but can be printed
Islower (c) lowercase letter
Isprint (c) printable characters
Ispunct (c) punctuation
Isspace (c) white space characters
Isupper (c) capital letters
Isxdigit (c) hexadecimal value
If tolower (c) is an uppercase letter, the return value is a lowercase letter. Otherwise, the return value is C.
Toupper (c) lowercase letters, returns uppercase letters; otherwise, returns C
// The number of punctuation marks in a given object
String S ("Hello word !!! ");
String: size_type punct_cnt = 0;
For (string: size_type Index = 0; index! = S. Size (); ++ index)
If (ispunct (s [Index])
++ Punct_cnt;
Cout <punct_cnt;

17: Standard Library vector type

A vector (container) is a collection of objects of the same type. Each object has a corresponding integer index value.
A vector is not a data type, but a class template. It can be used to define and initialize a vector object.

Several Methods for initializing a vector object
Vector <t> V1; an object whose vector persistence type is T. The default constructor V1 is empty.
Vector <t> V2 (V1); V2 is a copy of V1.
Vector <t> V3 (n, I); V3 contains n elements whose values are I.
Vector <t> V4 (n); V4 contains N copies of the elements whose values are initialized.
1. Create a number of elements.
If copying is performed, the two vectors must save the same element type.
Vector <int> ivec1; // ivec holds objects of Type int
Vector <int> ivec2 (ivec1); // OK: Copy elements of ivec1 into ivec2
Vector <string> SVEC (ivec1); // error: SVEC holds strings, not ints

Vector <int> ivec4 (10,-1); // 10 elements, each initialized to-1
Vector <string> SVEC (10, "Hi! "); // Strings, each initialized to" hi"
2. Value Initialization
Vector <int> fvec (10); // 10 elements, each initialized to 0
Vector <string> SVEC (10); // 10 elements, each an empty string
Operations on a vector object
1. The size of the vector object
Vector <int>: size_type // OK
Vector: size_type // erro
Size_type: it must be noted that this type is defined there.
2. add elements to the vector
String word;
Vector <string> text;
While (CIN> word)
{
Text. push_back (Word );
}
3. subscript operation of Vector
For (vector <int >:: size_type IX = 0; ix! = Ivec. Size (); ++ IX)
Ivec [ix] = 0;
4. subscript operations do not add elements
Vector <int> ivec;
For (vector <int >:: size_type IX = 0; ix! = 10; ++ IX)
Ivec [ix] = IX;
Subscripts can only obtain existing elements.
Correct syntax:
For (vector <int >:: size_type IX = 0; ix! = 10; ++ IX)
Ivec. push_back (IX );

Warning only subscript operations can be performed on elements that are known to exist
Vector <int> ivec; // empty vector
Cout <ivec [0] // error: ivec has no elements!

Vector <int> ivec2 (10); // vector with 10 elements
Cout <ivec [10]; // error: ivec has elements 0... 9

18. Introduction to the iterator

1. Container iterator type
Vector <int>: iterator ITER;
2. begin and end operations
Vector <int>: iterator iter = ivec. Begin ();
3. dereference operation
For the iterator type, you can use the unreferenced operator (* operator) to access the elements pointed to by the iterator.
* Iter = 0;
4. Example
Subscript operation method:
For (vector <int >:: size_type IX = 0; ix! = Ivec. Size (); ++ IX)
Ivec [ix] = 0;
Iterator:
For (vector <int >:: iterator iter = ivec. Begin (); iter! = Ivec. End (); ++ ITER)
* Iter = 0; 5. const_iterator
5. Read-Only elements in the container.
For (vector <string >:: const_iterator iter = text. Begin (); iter! = Text. End (); ++ ITER)
Cout <* ITER <Endl;
6. Do not confuse the const_iterator object with the const iterator object. When declaring a const iterator, The iterator must be initialized. Once initialized, its value cannot be changed.
Vector <int> Nums (10); // Nums is nonconst;
Const vector <int >:: iterator CIT = nums. Begin ();
* CIT = 1; // OK: CIT can change its underlying element
++ Cit; // error: Can't change the value of CIT
7. The const_iterator object can be used for const vector or non-const vector.
Const vector <int> nines (10, 9); // cannot change elements in nines
// Error: cit2 cocould change the element it refers to and nines is const
Const vector <int >:: iterator cit2 = nines. Begin ();

// OK: It can't change an element value, so it can be used with a const vector <int>
Vector <int>: const_iterator it = nines. Begin ();
* It = 10; // error: * It is const;
+ + It; // OK: It isn' t const so we can change its value
Note:
// An iterator that cannot write Elements
Vector <int>: const_iterator
// An iterator whose value cannot change
Const vector <int >:: iterator
8. Arithmetic Operations of the iterator
1. ITER + n
ITER-n
The position of n elements before or after the specified Element (+.
2. The signed type value of iter1-iter2 difference_type.
The intermediate element located in the vector
Vector <int>: iterator mid = VI. Begin () + VI. Size ()/2
Any operation to change the length of a vector will invalidate the existing iterator. For example, after push_back is called, The iterator value pointing to the vector cannot be considered again.

19. Standard Library bitset type
Process an ordered set of binary bits.
# Include <bitset>
Using STD: bitset;
1. Definition and initialization
Bitset <32> bitvec; // 32 bits, all zero
Bitset <n> B; // B has n digits, each of which is 0.
Bitset <n> B (U); // B is a copy of the unsigned Long U.
Bitset <n> B (s); // B is a copy of the bits contained in String object S.
Bitset <n> B (S, POs, n) // B is a copy of the N-digit starting from position POs in S.
2. Use the unsigned value to initialize the bitset object.
When the unsigned long value is used as the initial value of the bitset object, the value is converted to the bitwise mode of the binary value. The bitset in the bitset object serves as a copy of this mode. if the length of a bitset is greater than the binary bit of the unsigned long value, the other higher-order bits are set to 0. If the length is smaller than that, only the lower-order bits are used. The higher-order bits that exceed the bitset value are discarded.
The hexadecimal value 0 xFFFF indicates that the binary value is sixteen 1 and sixteen 0 (each 0xf can be expressed as 1111). You can use 0xffff to initialize the bitset object.
// Bitvec1 is smaller than the initializer
Bitset <16> bitvec1 (0 xFFFF); // bits 0... 15 are set to 1
// Bitvec2 same size as initializer
Bitset <32> bitvec2 (0 xfffff); // bits 0... 15 are set to; 16... 31 are 0
// On a 32-bit machine, BITs 0 to 31 initialized from 0 xFFFF
Bitset <128> bitvec3 (0 xfffff); // bits 32 through 127 initialize to zero
3. Use a String object to initialize a bitset object
Reads the bitset from string from right to left.
String strval ("1100 ");
Bitset <32> bitvec4 (strval );
In bitvec4 bit mode, the positions 2nd and 3 are 1, and the remaining values are 0. If the number of characters of the string object is smaller than the length of the bitset type, the higher level bit is set to 0.

String STR ("111111000011110000 ");
Bitset <32> bitvec5 (STR, 5, 4); // 4 bits starting at STR [5], 1100
Bitset <32> bitvec6 (STR, str. Size ()-4); // use last 4 characters

4. bitset object operations
B. Whether any () has a binary value set to 1
B. None () does not have a binary bit set to 1?
Number of binary bits where B. Count () is set to 1
B. Size () binary number
B [POS] accesses the binary position at the POs in B.
B. Test [POS] B. Is the binary position in POS 1?
B. Set () all binary bits are set to 1
B. Set (POS): Set the binary value of B at the POs to 1.
B. Reset () sets all binary values in B to 0.
B. Reset (POS) sets the binary position of B in POS to 0.
B. Flip () binary bitwise Inversion
B. Obtain the inverse of the flip (POS) POS.
B. to_ulong () returns an unsingned long value with the same binary value in B.
OS <B Outputs the bitset in B to the OS stream

Array and pointer

 





 

 

 



 

 

Related Article

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.