ch3 strings, vectors and arrays

1. Namespace using declaration

  • In the form of using declaration:
using namespace::name;
  • Header files should not contain using declarations

2. Standard library type string

1. String initialization
string s3("value") //s3 is a copy of the literal value "value", except for the empty character at the end of the literal value.
  • If you initialize a variable with an equal sign (=), what you actually do is copy initialization, and the compiler copies the initial value on the right side of the equal sign into the newly created object. If no equal sign is used, direct initialization is performed.
2. String object operation
getline(is, s) //Read a line from is and assign it to s, return is
s[n] //Returns a reference to the nth character in s, with position n counting from 0.
Read and write string objects
  • string objects automatically ignore the opening blanks (i.e. spaces, newlines, tabs, etc.) and start reading from the first real character until they meet the next blank.
  • string::size_type is a value of unsigned type and can store the size of any string object sufficiently
Compare string objects
  • If two string objects are not identical in some corresponding positions, the result of comparing string objects is actually the result of comparing the first pair of dissimilar characters in string objects.
Add literal values to string objects
string s4 = s1 + ", ";      // Right: Add a string object to a literal value  
string s5 = "hello" + ", ";     // Error: Neither operation object is a string  
  • You must ensure that at least one of the objects on either side of each addition operator (+) is a string.
3. Processing characters in string objects
Scope for statement
//The expression part is an object that represents a sequence.
//The declaration section defines a variable that will be used to access the underlying elements in the sequence
for (declaration : expression)  
    statement 

string str("some string");  
// Each line outputs a character in str.  
for (auto c : str)          // For each character in str  
     cout << c << endl;         // Output the current character, followed by a newline character    
Changing Characters in Strings
  • To change the value of characters in string objects, loop variables must be defined as reference types
string s("Hello World!!!");  
// Convert to capitalization.  
for (auto &c : s)       // For each character in s (note: c is a reference)  
    c = toupper(c);         // c is a reference, so the assignment statement changes the value of the character in s  
cout << s << endl; 
  • There are two ways to use a single character in a string object: one is to use subscripts, the other is to use iterators.
  • Before accessing the specified character, first check whether s is empty

3. Standard library type vector

  • The standard library type vector represents a collection of objects, all of which have the same type.
1. Initialize vector
#include <vector> 
using std::vector;

vector<int> ivec;               // ivec saves objects of type int  
vector<Sales_item> Sales_vec;   // Save objects of Sales_item type  
vector<vector<string>> file;    // The element of the vector is a vector object 
2. Adding elements to vector s
vector<int> v2;      // Empty vector object  
for (int i = 0; i != 100; ++i)  
    v2.push_back(i); // Put the integer values at the end of v2 in turn  
// At the end of the cycle, v2 has 100 elements, ranging from 0 to 99
  • push_back is responsible for pressing a value as the tail element of the vector object to the tail of the vector object.
  • vector supports subscript operations, but cannot add elements as Subscripts

4. Iterator Introduction

1. Using iterators
// b denotes the first element of v, e denotes the next position of the tail element of V  
auto b = v.begin(), e = v.end(); //The types of b and e are the same 
  • If the container is empty, begin and end return the same iterator, both tail iterators
Operators of standard container iterators
* iter // Returns a reference to the element referred to by iterator iter
 iter - > mem // dereference iter and obtain a member named mem of the element.
Equivalent to (* iter).mem
  • Use an iterator to change the first letter of a string object to uppercase
string s("some string");  
for (auto it = s.begin(); it != s.end() && !isspace(*it); ++it) { 
    *it = toupper(*it); // Change the current character to uppercase  
}
iterator types
vector<int>::iterator it;   // it can read and write elements of vector < int >  
string::iterator it2;       // it2 can read and write characters in string objects  

vector<int>::const_iterator it3;    // it3 can only read elements, not write elements
string::const_iterator it4;         // it4 can only read characters, not write characters  
2. Iterator operation
  • cbegin() and cend()
auto it = v.cbegin(); // it The type is vector<int>::const_iterator 
Two cases invalidate the iterator
  • You cannot add elements to a vector object in a scope for loop
  • Any operation that may change the capacity of a vector object, such as push_back, invalidates the iterator of the vector object

5. Arrays

1. Define and initialize built-in arrays
  • Dimensions must be a constant expression
int arr[10];                // Numbers with 10 integers
string bad[cnt];            // Error: cnt is not a constant expression
Explicit initialization of array elements
int a3[5] = {0, 1, 2};          //Equivalent to a3[] = {0, 1, 2, 0, 0}  
string a4[3] = {"hi", "bye"};   // Equivalent to a4[] = {"hi", "bye", ""} 
The Particularity of Character Array
  • It is important to note that there is an empty character at the end of the literal value of the string.
char a1[] = {'C', '+', '+'};        // List initialization, no empty characters  
char a2[] = {'C', '+', '+', '\0'};  //List initialization with explicit null characters  
char a3[] = "C++";                  // Automatically add empty characters indicating the end of a string  
const char a4[6] = "Daniel";        // Error: No space to store empty characters! 
Copying and assignment are not allowed
  • You cannot copy the contents of an array to other arrays as their initial values, nor can you assign values to other arrays.
int a[] = {0, 1, 2};    // Arrays with three integers  
int a2[] = a;           // Error: Initialization of another array with one array is not allowed  
aa2 = a;                // Error: You cannot assign an array directly to another array 
Complex array declaration
int *(&arry)[10] = ptrs; // Array is a reference to an array that contains 10 pointers 
2. Accessing array elements
  • subscripting
3. Pointer and array
string nums[] = {"one", "two", "three"}; // The element of an array is a string object  
string *p = &nums[0];  // p points to the first element of nums
string *p2 = nums; // Equivalent to P2 = & nums [0] 
Pointer is also an iterator
int arr[] = {0,1,2,3,4,5,6,7,8,9};  
int *p = arr;   // p points to the first element of arr  
++p;            // p points to arr[1] 
int *e = &arr[10]; //A pointer to the next position of the arr tail element 

int ia[] = {0,1,2,3,4,5,6,7,8,9}; // ia is an array of 10 integers 
int *beg = begin(ia);       // A pointer to the first element of ia  
int *last = end(ia);        //A pointer to the next position of the arr tail element 
Pointer operation
  • Add (subtract) an integer value to (from) a pointer, and the result is still a pointer. The element pointed by the new pointer moves forward (backwards) compared with the original pointer, and the integer value is positioned.
  • Like iterators, the subtraction of two pointers results in the distance between them.
  • As long as two pointers point to the element of the same array, or to the next position of the tail element of the array, they can be compared using the relational operator.
Interaction between dereference and pointer operation
int ia[] = {0,2,4,6,8};     // Contain5Array of integers  
int last = *(ia + 4);   // Correct:lastInitialize to8,that is ia[4]Value 
last = *ia + 4; // Correct: last = 4Equivalent to ia[0] + 4 
Subscripts and pointers
int i = ia[2];      // ia converts to a pointer to the first element of an array  
                   // ia[2] obtains the element referred to by (ia + 2)  
int *p = ia;        // p points to the first element of ia  
i = *(p + 2);       // Equivalent to i = ia[2] 


int *p = &ia[2];    // p points to the element with index 2  
int j = p[1];       // p[1] is equivalent to * (p + 1), which is the element represented by ia[3].  
int k = p[-2];      // p[-2] is the element represented by ia[0].  

6. Multidimensional Arrays

Initialization of multidimensional arrays
  • Initialize multidimensional arrays with a set of values enclosed in curly brackets, just like regular arrays
  • You can also remove curly braces
  • Initialize the first element of each line
int ia[3][4] = {{ 0 }, { 4 }, { 8 }}; 
  • Initialize line 1
int ia[3][4] = {0, 3, 6, 9 };
Subscript references to multidimensional arrays
// Assign the first element of arr to the last element of the last line of ia  
ia[2][3] = arr[0][0][0];  
int (&row)[4] = ia[1]; // Bind row to the second four-element array of ia
Pointer and Multidimensional Array
int ia[3][4];       //An array of three sizes, each element being an array of four integers int (* p) [4] = ia; // P points to an array of four integers  
p = &ia[2];             // p points to the tail element of ia
  • tips: Two-dimensional arrays must specify the number of columns, the number of rows can not be specified

Posted by JohnResig on Wed, 03 Jul 2019 17:04:04 -0700