3rd chapter string, vector, array

Source: Internet
Author: User
Tags control characters

3.2 string

Initialization

stringS1;//default initialization, S1 is an empty stringstringS2 (S1);//Initialize s2 with s1stringS2=S1;//Ibid .stringS3 ("value");//S3 is a copy of the literal "value", but does not include thestrings3="value";//Ibid .stringS4 (Ten,'C');//use 10 c to initialize a S4

Operation

os<<STR//writes STR to the output stream and returns to the OS is>>str//assigns the string space read in is to STR and returns the isGetline ( is, str)//reads a row from is to STR, the newline character is also read (the position in the stream after the newline character), but is not assigned to STRStr.empty () str.size ( )//returns the number of charactersStr[n]//returns a reference to the nth character in Strstr1+STR2STR1=str2//Replace the str2 copy with the contents of the STR1str1==STR2STR1!=str2&lt, <=, >=

Warming

String::size_type string::size ();

The size function returns the Size_type type, which is actually an unsigned type, so you should pay attention to the comparison with negative numbers:

Expression: Str.size () <-1, returns true because 1 needs to be converted to unsigned for comparison.

Str1+str2

Literals cannot be added, such as "ASD" + "1256"

Warming

The type of string is different from the type of string "string", which is char[]

Handling characters

Use the following statement to process:

 for (Auto c:str) {    statement ...}
Isalnum (c)//true if C is a letter or a numberIsalpha//LettersIscntrl//control charactersIsDigit//DigitalIsgraph//not a space, but can be printedIslower//Lowercase LettersIsprint//printable, including spacesIspunct//PunctuationIsspace//White space charactersIsupper//Uppercase LettersIsxdigit//hexadecimal digitsToLower//into lowercaseToUpper//into uppercase

Warming

Just for the range-based for loop, just get a copy of the characters in string, and if you want to change the value in string, you must use a reference:

for (auto &c:s)

3.3 Vector Container

#include <vector>using std::vector;

A vector is a class template.

The template itself is not a class or function, it is a description of the class or function, and the compiler creates the class or function (the process is called instantiation) according to the description (described in angle brackets).

A vector can accommodate an object of a large number of types, but the reference is not an object and cannot be included.

Warming

In earlier versions of the compiler, if vectors were stored in the vector, the inner angle brackets needed to be separated by spaces, such as:vector< vector<int> >

Initialization

Vector<t> v1;    // v1 is an empty vector, type T, which performs the default initialization of vector<t> v2 (v1);    // v2 contains all the elements in the V1 vector<t> v2 = v1;    // Ibid . vector<t> v3 (n, Val);    // v3 contains n repetitions of Valvector<t> v4 (n);    // v4 contains n duplicate default initialized T objects, must be able to have default initialinitialization of T vector<t> V5{a, B, C, d};    // v5 contains the initial values vector<t> V5={a, B, C, d};    // Ibid .

Warming

Vector<string> v_str ("Hello");

This statement is wrong because "hello" is char[] and there is no way to initialize string.

vector<string> v_str {"Hello"}

This is correct, you can initialize a vector of string with a list

Vector<string> V_str {ten, "Hello"}

This is correct, initialization always 10 the same "Hello"

Vector operation

/*Note that when you perform a press-in, the end judgment of the V1 is changed, especially in the range for statement, where errors may occur*/V1.push_back (t); //Press T into the tail of the V1V.empty (); //judgment does not contain any elements and returns trueV.size ();//Number of elementsV[n];//Get nth elementV1 = v2;//Replace all elements of V1 with copies of V2 elementsV1 = {A,b,c,d};//Ibid .V1 = = V2;//when and only if the number of V1, V2 elements is the same, and the corresponding elements are the sameV1! =v2;&lt, <=, >=

3.4 iterators

Iterators provide indirect access to objects. A valid iterator points to an element, or to the next position of the tail element, and the other is an invalid iterator.

 for (Auto iter = V.begin (); ITER! = V.end (); +iter)    {*iter = (*iter) +5;}

Iterator operations

V.begin ();//An iterator that returns the first element of a containerV.end ();//an iterator that returns the next element of a container's tail elementV.cbegin ();//An iterator that returns the first element of a container, which cannot be modified in constant formV.cend ();//an iterator that returns the next element of the container's tail element, which cannot be modified in constant form*iter;//returns a reference to the indicated elementiter->member;//Dereference and return the member member of the element it refers to, same as (*iter). Member++iter;//refers to a downward element--iter;//point to previous elementIter+n;//beyond the last element will not be an errorIter-n;//exceeding the first element will not be an errorIter1-iter2;//distance between two iteratorsIter1= = Iter2;//Judging is the same elementIter1! =Iter2;, >=, <, <=//determine the position of the front and back

The types of iterators are divided into iterator and const_iterator, such as: Vector<int>::iterator ITER;

The distance type of the iterator is Difference_type, which is a signed integer type.

If the container is empty, begin and end return the next position of the trailing element.
If the container is a constant, the begin and Cbegin return are constant forms, and end is the same.

3.5 arrays

As with vectors, the elements of an array cannot be references. Declaration of complex arrays

At compile time, you need to know the size of the array, so the dimension should be constant when the array is initialized.

As with other built-in types (int, double), arrays are not initialized until they are defined outside the function, and are not initialized when defined within a function. In order to initialize the array by default, an empty list can be assigned to the array.

int a[]={123};    // Explicit Initialization int a[]={};    // explicit initialization, 0 after initialization int d[]=a;    // error, cannot copy int size=sizeof(a)/sizeof(*a);    // get the size of an array

Declaration of complex arrays

int *ptrs[];    // storage of 10 plastic pointers int (*parray) [ten] = &arr;    // Parray pointing to an array with 10 shaping int (&ARRREF) [ten] = arr;    // Arrref is a reference that contains 10 shaped arrays int * (&arrref) [ten] = arr;    // Arrref is a reference to an array with 10 pointers in the array

Access to arrays

The array subscript is of type size_t, defined in the <cstddef> header file, which is designed to be large enough to represent the size of any object in memory.

Pointers and Iterators

The compiler typically treats the array name as a pointer to the first element.

A function named begin and end is defined in header file <iterator> to get the pointer of the hand element of the array and a pointer to the next position of the tail element.

int a[]={};  for (int *pbeg=begin (a);p beg!=end (a);p beg++)    cout<< (*pbeg) <<endl;

Two pointers are subtracted to get the distance between them, and the two pointers must also be pointers to elements in the same array.
This distance is type ptrdiff_t, defined in <cstddef>.

C-style string

A sequence of characters in an array of type char that ends with a '/s ' character. All of its operations are done through the functions in <cstring>.

C + + interface

//C strings can be converted to string by constructors//string can be converted to C string by C_str () functionCharCstr[] ="string";stringcppstr (CSTR);Const Char*CTR =cppstr.c_str ();//to initialize a vector with an array, simply specify the address of the arrayintint_arr[]={1,2,3,4,5};vector<int> Ivec (Begin (Int_arr), End (Int_arr));

3.6 Multi-dimensional arrays

A multidimensional array is actually an array of arrays. When defined, the default initialization can be followed by an empty list.

Why are multidimensional arrays required to have the same number of elements in each dimension? Because the array requires the same type stored in it, the beginning of the array type contains the length of the array, so each number requires the same.

For a two-dimensional array, the first dimension is often a row, and the second dimension is called a column.

Warming

When using the range for loop to iterate over a multidimensional array, other than the most inner loop, the reference traversal is used to prevent the array from being automatically converted to pointers.

 for & row:table)      for (auto Line:row)        cout<<line<<endl;

If auto is not used in the outer for loop, you need to indicate the type for the inner dimension in the two-dimensional array.

For example, for int table[10][5], you need to know that the inner dimension is int[5], so the type of auto should be int[5]. However, if you write int row[5], each iteration, the iterator assigns a copy of the current dimension in the table to row, and since the array cannot be directly assigned, only references to int[5] can be used here:

 for int (*row) [5] : table)      for int Line:row)        cout<<line<<endl;

3rd chapter string, vector, array

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.