C++ primer review Chapter 3 strings, vectors and arrays

Chapter 3 string, vector and array

3.1 namespace using

The header file should not contain the using declaration because it will be copied to other files

Namespace declaration: using namespace::name;

#include<iostream>

int main(){
	std::cout << "Enter two number" << std::endl;

	int v1, v2;
	std::cin >> v1 >> v2;

	std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl;
	return 0;
}
#include<iostream>
using std::cin;
using std::cout; using std::endl;

int main(){
	cout << "Enter two number" << endl;

	int v1, v2;
	cin >> v1 >> v2;

	cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << endl;
	return 0;
}

3.2 standard library type string

Standard library type string: a character sequence with variable length, including a string header file

Definition and initialization

#include<iostream>
#include<string>
using std::string;

int main(){
	string s1;         //Empty string
	string s2 = s1;    //Copy, copy construction, equivalent to string s2(s1)
	string s3 = "aaa"; //Copy, equivalent to string s3("aaa")
	string s4(3, 'a'); //Equivalent to aaa

	return 0;
}

Operation on string object

string s1, s2;
std::cin >> s1 >> s2;
std::cout << s1 << s2 << std::endl;

Print results

Hello
World
HelloWorld
 Please press any key to continue. . .

A newline is treated as the end of a string

string word;
while (std::cin >> word)
{
	std::cout << word << std::endl;
}

Print results

Hello
Hello
World
World

Add literal and string objects

String literals in C + + are const char*

string s1 = "Hello",s2 = "World";
string s3 = s1 + "," + "s2" + "\n";

string s4 = s1 + ",";
string s5 = "Hello" + "World"; //report errors

Functions in cctype header file (ctype.h)

C + + names the contents in the C language standard library cname (excluding. h)

Functions in cctype header file (ctype.h)

/*
	Statistical punctuation
*/
std::string s("HELLO WORLD!!!");
//unsiged
decltype(s.size()) count = 0;

for (auto c : s){
	if (ispunct(c)){
		++count;
	}
}
std::cout << "The count is " << count << std::endl;

In the advanced for loop, auto is used without changing the original value; Change the value of the container element and use auto&

/*
	Convert case
*/
std::string s1 = s;
for (auto& c : s1){
	if (isupper(c)){
		c = tolower(c);
	}else{
		c = toupper(c);
	}
}
std::cout << s1 << std::endl;
/*
	Convert case only before spaces
*/
std::string s2 = s;
decltype(s2.size()) index = 0;
while (index != s2.size() && !isspace(s2[index]))
{
	if (isupper(s2[index])){
		s2[index] = tolower(s2[index]);
	}else{
		s2[index] = toupper(s2[index]);
	}

	++index;
}
std::cout << s2 << std::endl;
/*
	(0 - 15) Decimal to hexadecimal
*/
const std::string bucket = "0123456789ABCDEF";

std::string result;

std::string::size_type number;
while (std::cin >> number){
	if (number < bucket.size()){
		result = bucket[number];
	}
}

std::cout << result << std::endl;

3.3 standard library type Vector

Standard library type vector: collection of objects. There is no vector containing references

Method to initialize vector object

In addition to being more concise, the advanced for loop avoids overflow

/*
	Square the element
*/

std::vector<int> v1{ 1, 2, 3, 4, 5, 6 };
for (auto& item : v1){
	item *= item;
}

Operations supported by vector

/*
	Enter a score of 0-100
	Segment: 0-9, 10-19... 90-99100
	Count the number of students in each section
*/
std::vector<unsigned> scores(11, 0); // 11 buckets,all initially 0
unsigned grade;
while (std::cin >> grade)
{
	++scores[grade / 10];
}

for (auto i : scores){
	std::cout << i << std::endl;
}

3.4 Iterator

Introduction to iterators

Like pointers, iterators can be used to access an element, and iterators can also be moved from one element to another

Iterator types have both begin and end members

begin: returns the iterator pointing to the first element

end: a trailing iterator that returns the next position of the last element (a position where there is no element)

If the container is empty, begin and end return the same iterator, both of which are trailing iterators

A trailing iterator does not point to an element, so it cannot be incremented or dereferenced

Iterator operator

/*
	toggle case
*/
std::string s("i like c++");
//Note the type of iterator declared
std::string::iterator it = s.begin();

while (it != s.end()){
	*it = toupper(*it);
	++it;
}

/*
	Case conversion before the first space
	FOR The loop will be more concise. For judging the loop jump out condition with increasing variables
*/
for(auto it =  s.begin(); it != s.end() && !isspace(*it) ; ++it){
	*it = toupper(*it);
}

iterator types

Iterators are standard types iterator and const_iterator (similar to constant pointers)

// it1 reads and writes elements of vector < int >
std::vector<int>::iterator it1;
// it2 can read and write string characters
std::string::iterator it2;

// it3 only reads the elements of vector < int > and cannot be written
std::vector<int>::const_iterator it3;

If object is a constant, begin and end return const_iterator, otherwise, it returns iterator;

std::vector<int> v1;
const std::vector<int> v2;
auto it1 = v1.begin(); //The type of it1 is STD:: vector < int >:: iterator
auto it2 = v2.begin(); //The type of it2 is STD:: vector < int >:: const_ iterator

Object is not a constant. Const is still used_ Iterator, C++11 introduces cbegin and cend

auto it2 = v1.cbegin(); //The type of it3 is STD:: vector < int >:: const_ iterator

Member access combined with dereference

Any operation that may change the capacity of the vector object will invalidate the iterator

std::vector<std::string> v;
//Type of it: STD:: vector < STD:: String >:: iterator
auto it = v.begin();
//After dereferencing, return the reference of the object and call the empty method of string
(*it).empty();

//it.empty();  error
// ->The arrow operator is equivalent to combining dereference and member access
it->empty();
/*
	Practice cbegin & cend & - >
*/
std::vector<std::string> v(3, "HELLO");

for (auto it = v.cbegin(); it != v.cend()&& !it->empty(); ++it){
	std::cout << *it << std::endl;
}

Iterator operation

vector and string iterators provide additional operators

To add (or subtract) an iterator from an integer, its return value is an iterator that moves several positions forward (or backward)

/*
	Binary search
*/

std::vector<int> v = { 0,1, 2, 3, 4, 5 };

int target = 2;
auto beg = v.begin(),end = v.end();
auto mid = beg + (end - beg) / 2;//The middle point in the initial state

while (mid != end && *mid != target) {
	if (target < *mid) {
		end = mid - 1;
	} else {
		beg = mid + 1;
	}
	mid = beg + (end - beg) / 2;
}

if (mid != v.end()) {
	std::cout << "eureka" << std::endl;
} else {
	std::cout << "not found" << std::endl;
}

3.5.1 array definition and access

Arrays: composite types

Declaration form array name [number of elements] example, Arr[N], N must be a constant expression

unsigned cnt = 42;
constexpr unsigned int sz = 1;//Constant expression
int arr[10];
int* ptr[sz];
// std::string bad[cnt];  Error, CNT is not a constant expression

There is no reference array. You can use list initialization, but you must specify the array type. auto is not allowed

constexpr unsigned sz = 3;//Constant expression
int arr1[sz] = { 0, 1, 2 };
int arr2[] = { 0, 1, 2 }; //Automatically infer that the number of elements is 3
int arr3[5] = { 0, 1, 2 };//Equivalent {0, 1, 2, 0, 0}
std::string arr4[3] = {"hi" , "bye"};//Equivalent {"Hi", "Bye", ""}
int arr5[2] = { 0, 1, 2 }; //Error, too many initial values

Character array particularity

The default end of a string is an empty character

char a1[] = { 'C', '+', '+' };//List initialization, no empty characters
char a2[] = { 'C', '+', '+', '\0' };//List initialization with empty characters displayed
char a3[] = "C++";//Contains empty characters
const char a4[6] = "Danial";//Error, there is no space for empty characters

Copy and assignment are not allowed

int a[] = { 0, 1, 2 };
//int a2[] = a;// Copy assignment is not allowed during initialization

Understanding complex array declarations

[] priority is higher than*

int *ptrs[10];//An array containing ten integer pointers
int&refs[10];//Error, no reference array exists
int(*parray)[10];//Points to an array of ten integers
int(&parray)[10] = arr;//Reference an array of ten integers
int*(&arry)[10] = ptrs;//Array, which contains ten integer pointers

3.5.2 pointer and array, C-style string

Pointers and arrays

The compiler usually turns an array into a pointer

std::string nums[] = { "one", "two", "three" };
std::string* p1 = &nums[0];//p points to the first element of num
std::string* p2 = nums;//Equivalent to P2 = & num [0]

int arr1[] = { 0, 1, 2, 4, 5 };//arr1 is an array of 5 integers
auto arr2(arr1);//arr2 is an integer pointer to the first element of arr1
arr2 = 42;//Error, arr2 is a pointer

//When decltype is used, the above conversion does not occur
decltype(arr1) arr3 = { 0, 1, 2 };
arr3 = arr2;//Error, cannot assign integer pointer to array
arr3[0] = -1;

Pointers are also iterators

This method can get the tail pointer, which is easy to make mistakes, so it is not recommended

int arr[] = { 0, 1, 2 };
int *p = arr;
++p;//p points to arr[1]
int* p1 = &arr[3];//Points to the next position of the arr tail element
  
for (int *b = arr; b != p1; ++b){
	std::cout << *b << std::endl;
}
/*
	Find the first negative number
*/
int arr1[] = { 0, 1, 2, 3, 4 };
int* beg = std::begin(arr1);
int* end = std::end(arr1);

while (beg != end && beg>0){
	++beg;
}

if (beg != end){
	std::cout << *beg << std::endl;
}

Dereference and pointer operation interaction

int arr1[] = { 0, 1, 2 };
int last = *(arr1 + 2);//last = 2
last = *arr1 + 4;//last = 4;

Subscript and pointer

Standard library types are restricted to use subscripts that cannot be negative, but built-in types do not have this requirement

Array (built-in) string, vector (STL Standard Library)

int arr1[] = { 0, 1, 2, 3, 4};
int i = arr1[2];//It is equivalent to the following two articles and fully understood

int *p = arr1;
i = *(p + 2);

int *p1 = &arr1[3];
int j = p1[1];//Equal to * (p1+1)
int k = p1[-2];//Equal to * (p1-2)

C style string

C-style string is not a type, but a conventional writing method

The C-style string handler is defined in the cstring header file

The string as a parameter must end with a null character

#include<cstring>

char str1[] = { 'C', '+', '+' };//Must end with a null character, fixed
std::cout << strlen(str1) << std::endl;

std::string s1 = "A string example";
std::string s2 = "A different string";

if (s1 < s2) {//false compares characters in dictionary order
std::cout << "s1 len less than s2 len " << std::endl;
}

const char* cstr1 = "A string example";
const char* cstr2 = "A different string";
if (cstr1 < cstr2) {//true compares the size of the array
	std::cout << "cstr1 len less than cstr2 len " << std::endl;
}

if (strcmp(cstr1, cstr2)<0){//It is the same as the above two string comparisons
	std::cout << "cstr1 len greater than cstr2 len " << std::endl;
}

Interface with old code

std::string s1("Hello World");
char* c_s2 = s1; //Error, cannot assign string object to char*
const char* c_s3 = s1.c_str();//Correct, convert string to c string

If the value of s1 is subsequently changed, then C_ The array returned by STR will become invalid

//Initializing a vector object with an array
int int_arr[] = { 0, 1, 2, 3 };
std::vector<int> vec1(std::begin(int_arr), std::end(int_arr));//{ 0, 1, 2, 3 }
std::vector<int> vec1(int_arr+1, int_arr+3);//{1,2,3}

3.6 multidimensional array

Multidimensional array: strictly speaking, C + + does not have multidimensional array. C + + multidimensional array is realized by array

int arr[3][4];//An array of size 3. Each element is an array containing 4 integers
int arr[10][20][30] = { 0 };//Initialize all elements to 0

initialization

A bracket is a line

//Allows you to initialize multidimensional arrays with curly braces
int arr2[2][2] = {
	{ 0, 1},
	{ 2, 3}
};

int arr3[2][2] = { 0, 1, 2, 3 };
int arr3[2][2] = { { 0 }, { 2 } };//0,0,2.0 
int arr3[2][2] = { 0, 2 }; //0,2,0,0

Subscript reference

Allows array elements to be arrays themselves

//Assign a value to the last element of the last row of arr0 with the first element of arr1
arr0[3][4] = arr1[0][0][0];

/*
	Initialize array elements
*/
constexpr size_t rowCnt = 3, colCnt = 4;
int arr4[rowCnt][colCnt];//12 uninitialized elements
for (size_t i = 0; i < rowCnt; ++i){
	for (size_t j = 0; j < colCnt; ++j){
		arr4[i][j] = i * rowCnt + colCnt;
	}
}

/*
	Change the array elements to 0 - 12
*/
size_t cnt = 0;
for (auto& row : arr4){
	for (auto& col : row){
		col = cnt;
		++cnt;
	}
}

//Using & can effectively prevent the fetched array from being automatically converted to a pointer by the compiler
for (auto row : arr4)
	for (auto col : row)//Error: int* row has no begin function

Pointers and multidimensional arrays

Two forms

int arr0[3][4] = {
	{0,1,2,3},
	{4,5,6,7},	
    {8,9,10,11}
};//An array of size 3. Each element is an array containing 4 integers

//Define int arr0[3][4]; 
// Arr0 type int(*)[4] arr0[0] type int*
int(*p)[4] = arr0;//Equivalent to int (* P) [4] = & arr0 [0];

/*
	Output arr0 each element value
 	Two forms
*/
for (auto p = arr0; p != arr0 + 3; ++p){
	for (auto q = *p; q != *p + 4; ++q){
		std::cout << *q << " ";
	}
	std::cout << std::endl;
}

for (auto p = std::begin(arr0); p != std::end(arr0); ++p){
	for (auto q = std::begin(*p); q != std::end(*p); ++q){
		std::cout << *q << " ";
	}
	std::cout << std::endl;
}

Type aliases simplify pointers to multidimensional arrays

using int_array = int[4];//typedef int int_array[4]
for (int_array *p = arr0; p != arr0 + 3; ++p){
	for (int *q = *p; q != *p + 4; ++q){
		std::cout << *q << " ";
	}
	std::cout << std::endl;
}

Attached with mind map

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-gm7cdzbn-1638196760935) (Chapter 3 string, vector and array. assets / Chapter 3 + string, vector and array. png)]

]Type int*
int(*p)[4] = arr0;// Equivalent to int (* P) [4] = & arr0 [0];

/*
Output arr0 each element value
Two forms
*/
for (auto p = arr0; p != arr0 + 3; ++p){
for (auto q = *p; q != *p + 4; ++q){
std::cout << *q << " ";
}
std::cout << std::endl;
}

for (auto p = std::begin(arr0); p != std::end(arr0); ++p){
for (auto q = std::begin(*p); q != std::end(*p); ++q){
std::cout << *q << " ";
}
std::cout << std::endl;
}

#### Type aliases simplify pointers to multidimensional arrays

```c++
using int_array = int[4];//typedef int int_array[4]
for (int_array *p = arr0; p != arr0 + 3; ++p){
	for (int *q = *p; q != *p + 4; ++q){
		std::cout << *q << " ";
	}
	std::cout << std::endl;
}

Attached with mind map

Tags: C++ Back-end

Posted on Mon, 29 Nov 2021 15:25:29 -0500 by JesuZ