《Beginning C++17》-学习笔记-Chapter 05-Arrays and Loops

点云处理提速秘籍:用Open3D和PCL对比实现体素降采样,哪个更适合你的项目? 本文深度对比了Open3D和PCL在体素降采样技术上的实现差异与性能表现,帮助开发者根据项目需求选择最佳工具。通过实测数据、API设计对比和特殊场景案例,揭示了两者在处理速度、内存管理及细节保留上的优劣,为点云处理提速提供实用指南。 阅读详情

The size of an array must always be specified using a constant integer expression. Any integer expression that the compiler can evaluate at compile time may be used, though mostly this will be either an integer literal or a const integer variable that itself was initialized using a literal.

The index of a particular array element is its offset from the first element. The first element has an offset of 0 and therefore an index of 0; an index value of 3 refers to the fourth array element—three elements from the first.

The type of the array will determine the amount of memory required for each element. The elements of an array are stored in one contiguous block of memory.

To define an array of values that cannot be modified, you simply add the keyword const to its type.

The values returned by the sizeof operator have type of size_t. It is an unsigned integer type that is generally used, for instance, for sizes and counts of things.

size_t is not the name of a built-in fundamental type such as int, long, or double; it is a type alias defined by the Standard Library. More specifically, it is an alias for one of the unsigned integer types, sufficiently large to contain the size of any type the compiler supports (including any array). The alias is defined in the cstddef header, as well as in a number of other headers. In practice, however, you mostly do not need to include (with #include) any of these headers explicitly to use the size_t alias; the alias is often indirectly defined already by including other more high-level headers (such as the iostream header).

Array index values are not checked to verify that they are valid. It’s up to you to make sure that you don’t reference elements outside the bounds of the array. If you store data using an index value that’s outside the valid range for an array, you’ll either inadvertently overwrite something in memory or cause a socalled segmentation fault or access violation (both terms are synonymous and denote an error that is raised by the operating system if and when it detects unauthorized memory access). Either way, your program will almost certainly come to a sticky end.

It is legal to define variables within a for loop initialization expression.

Any automatic variables declared within the scope of a loop do not exist outside it.

 

//两种计算array中element个数的方法
#include <iostream>
#include <array>          // for std::size();

int main()
{
	int values[]{ 10, 10, 10, 10};

	std::cout << "Number of elements in the array is: " << sizeof(values) / sizeof(values[0]) << std::endl;/*sizeof operator returns the number of bytes that a variable occupies. This works with an entire array as well as with a single array element.*/

	std::cout << "Number of elements in the array is: " << std::size(values) << std::endl;
}

The standard formula \pi r^{^{2}} is used to calculates the area of a circle.

Any number that is a fraction with an odd denominator cannot be represented exactly as a binary floating-point value. 0.2 cannot be represented exactly in binary floating point.

Comparing floating-point numbers can be tricky. You should always be cautious when comparing the result of floating-point computations directly using operators such as ==, <=, or >=. Rounding errors almost always prevent the floating-point value from ever becoming exactly equal to the mathematical precise value.
 


The factorial of an integer n, written n!, is the product of all the integers from 1 to n; for example, 5! = 1 × 2 × 3 × 4 × 5 = 120.


The comma is a binary operator. It combines two expressions into a single expression, where the value of the operation is the value of its right operand. This means that anywhere you can put an expression, you can also put a series of expressions separated by commas.

#include <iostream>

int main()
{
	std::cout << (1,2,3,4,5) << std::endl;//输出最后一个数字5
}

 


What is a range? An array is a range of elements, and a string is a range of characters. The containers provided by the Standard Library are all ranges as well.

#include <iostream>

int main()
{
	int range_1[]{ 1, 1, 1, 1, 1};
	int total_1{};
	for (int x : range_1)
	{
		total_1 += x;
	}
	std::cout << total_1 << std::endl;//输出5

	int total_2{};
	for (auto x : { 1, 1, 1, 1, 1 })//A braced initializer list itself is a valid range
	{
		total_2 += x;
	}
	std::cout << total_2 << std::endl;//输出5

}

#include <iostream>

int main()
{
	int n{};
	int sum{};
	while (++n <= 3)// variable n is first incremented, then compared with integer literal 3.
	{
		sum += n; 
	}
	std::cout << sum<< std::endl;//输出6

}

#include <iostream>
#include <cctype>    /* For tolower() function,也可以改为#include <locale>*/

int main()
{
	char reply{};                                      // Stores response to prompt for input
	int count{};                                       // Counts the number of input values
                               
	do
	{
		std::cout << "You ate " << ++count << ((count ==1)?" apple":" apples") << std::endl;     

		std::cout << "Do you want to eat another apple? (y/n): ";
		std::cin >> reply;                                // Get response

	} while (tolower(reply) == 'y');//此处必须加一个分号

	std::cout << "You ate " << count << ((count == 1) ? " apple" : " apples") << " in total." << std::endl;
}

//利用nested loops 输出10x10乘法表
#include <iostream>
#include <iomanip>

int main()
{

	for (size_t i{ 1 }; i <= 10; ++i)
	{   
		std::cout << std::setw(3) << i << "|"; // Start the row
		
		for (size_t j{ 1 }; j <= 10; ++j)
		{
			std::cout << std::setw(3) << i * j << "|";  // Output the values in a row.
		}
		std::cout << std::endl; 
	}

}

/*This outputs all the printable characters with code values from 0 to the maximum unsigned char value so it displays a handy list of the codes for the printable ASCII characters.*/
#include <iostream>
#include <iomanip>
#include <cctype>
#include <limits>

int main()
{
	// Output the column headings
	std::cout << std::setw(11) << "Character " << std::setw(13) << "Hexadecimal "
		<< std::setw(9) << "Decimal " << std::endl;
	std::cout << std::uppercase;                                      // Uppercase hex digits

	// Output characters and corresponding codes
	unsigned char ch{};
	do
	{
		if (!std::isprint(ch))                                           // If it's not printable...the isprint() function only returns true for printable characters.
			continue;                                                      // ...skip this iteration
		std::cout << std::setw(6) << ch                                  // Character
			<< std::hex << std::setw(12) << static_cast<int>(ch)   // Hexadecimal
			<< std::dec << std::setw(10) << static_cast<int>(ch)   // Decimal
			<< std::endl;
	} while (ch++ < std::numeric_limits<unsigned char>::max()); /*numeric_limits<>::max() function returns the maximum value for the type you place between the angled brackets.*/
}

// Sorting an array in ascending sequence - using an indefinite while loop
#include <iostream>
#include <iomanip>

int main()
{
	const int array_size{ 10 };
	int x[array_size]{10,9,8,7,6,5,4,3,2,1};                    
		
	std::cout << "Starting sort..." << std::endl;
	//bubble sort algorithm
	while (true)
	{
		bool swapped{ false };          
		for (size_t i{}; i < array_size-1; ++i)
		{
			if (x[i] > x[i + 1])          
			{
				const auto temp = x[i];
				x[i] = x[i + 1];
				x[i + 1] = temp;
				swapped = true;
			}
		}

		if (!swapped)                   // If there were no swaps, data are in order; otherwise, go round again.

	std::cout << "Result:\n";
	for (size_t i{}; i < array_size -1; ++i)
	{
		std::cout << std::setw(3) << x[i];
	}

	std::cout << std::endl;
}

/*A character array that is terminated by '\0' is referred to as a C-style string. */
#include <iostream>
#include <iomanip>

int main()
{

	int int_array[]{ 1, 2, 3, 4,5 };
	char char_array1[]{ 'a','i','o','u' };
	char char_array2[]{ "aiou" };/*array initiated with a string literal; the null character will be stored in the element following the last string character,*/

	std::cout << int_array <<std::endl;//输出乱码
	std::cout << char_array1 << std::endl; //输出aiou以及一些乱码
	std::cout << char_array2 << std::endl;/*输出aiou. You can output a string stored in an array just by using the array name. 
						There must be a '\0' at the end of the array. If there isn’t, the standard output stream 
						will continue to output characters from successive memory locations, which almost certainly 
						contain garbage, until either a null character happens to turn up or an illegal memory access occurs.*/

}

#include <iostream>
#include <cctype>

int main()
{
	const int max_length{ 100 };              // Array size
	char text[max_length]{};                // Array to hold input string

	std::cout << "Enter a line of text:" << std::endl;

	std::cin.getline(text, max_length);		// Read a line of characters including spaces
        /* The getline() function for cin reads a sequence of characters, including 
spaces. By default, the input ends when a newline character, '\n', is read, which will 
be when you press the Enter key. The getline() function expects two arguments between 
the parentheses. The first argument specifies where the input is to be stored, which in 
this case is the text array. The second argument specifies the maximum number of 
characters that you want to store. This includes the string termination character, '\0', 
which will be automatically appended to the end of the input.*/
	std::cout << "You entered:\n" << text << std::endl;//输出之前输入的所有字符

}

#include <iostream>
#include <array>   //this header defines  array<T,N> template

int main()
{
	std::array<double, 100> values; //This creates an object that has 100 elements of type double.
	values.fill(1);//set all elements to 1.
	std::cout << values.size() << std::endl;// return the number of elements of variable values.

	//using range-based for loop to sum up all elements in values.
	int total{};
	for (auto w : values)
	{
		total += w;
	}
	std::cout << total <<std::endl;

	std::array<double, 100> values2 =values; //copy all elements of values to values2;
	std::cout << values2.at(99) << std::endl;// return the number of elements of variable values.

	std::cout << values[2] << std::endl;// return the value of the third element, which is 1.
	std::cout << values.at(2) << std::endl;/*return the third element as well; at() function for an array<> object will detect attempts to use an index value outside the legitimate range*/
	std::cout << ( values.front() == values[0] )<< std::endl;
	std::cout << ( values.back() == values[values.size() - 1] ) << std::endl;

	//using for loop to sum up all the elements in an array.
	double total1{};
	for (size_t i{}; i < values.size(); ++i)
	{
		total1 += values[i];
	}
	std::cout << total1 << std::endl;//return the sum of all elements , which is 100
	//using range-based for loop to sum up all the elements in an array.
	double total2{};
	for (auto value : values)
	{
		total2 += value;
	}
	std::cout << total1 << std::endl;//return the sum of all elements , which is 100

}

#include <iostream>
#include <vector>   //including this header for using the vector<> container 

int main()
{
	std::vector<double> values(20); //creating a vector<> container that contains 20 values of type double, all initialized to 0
	values.push_back(3.1415); // Add an element to the end of the vector
	std::cout << values.size() << std::endl;//output 21

	std::vector<long> numbers(20, 99L); // Initialize a vector that contains 20 long values - all 99
	std::cout << numbers.size() << std::endl;//output 21
	std::vector<long> numbers2;
	numbers2.assign(99, 20L); //  Using assign() functions reinitialize the contents of a vector that contains 99 long values - all 20
	std::cout << numbers2.size() << std::endl;//output 99

	std::vector<int> data(100, 99); // Contains 100 elements initialized to 99
	data.clear(); // Remove all elements
	std::cout << data.size() << std::endl;//output 0

	std::vector<int> data2(100, 99); // Contains 100 elements initialized to 99
	data2.pop_back(); // Remove the last element
	std::cout << data2.size() << std::endl;//output 99

}

 


// using a vector<T> container to store numbers
#include <iostream>
#include <iomanip>
#include <vector>

int main()
{
	std::vector<double> x;               // Stores data to be sorted

	while (true)
	{
		double input{};                   // Temporary store for a value
		std::cout << "Enter numbers you want to store one after another; enter a non-zero value, or 0 to end: ";
		std::cin >> input;
		if (input == 0)
			break;

		x.push_back(input);
	}

	std::cout << "Your entered the following data.\n";

	for (size_t i{}; i < x.size(); ++i)
	{
		std::cout << std::setw(8) << x[i];

	}
	std::cout << std::endl;
}

 


The range-based for loop iterates over all elements within a range. An array is a range of elements, and a string is a range of characters. The array and vector containers define a range so you can use the range-based for loop to iterate over the elements they contain.


#include <iostream>
#include <iomanip>

int main()
{
	std::cout << "显示4位小数: "  << std::setprecision(4) << std::fixed << (static_cast<double>(4)) << std::endl;
	//std::fixed Output floating-point data in fixed-point notation.
	/*std::setprecision(n) Sets the floating-point precision or the number of decimal places to n digits.
	If the default floating - point output presentation is in effect, n specifies the
		number of digits in the output value.If fixed or scientific format has
		been set, n is the number of digits following the decimal point.The default
		precision is 6*/
}

#include <iostream>

int main()
{
	unsigned count{};
	char ch{};

	std::cout << "Please enter a sequence of characters terminated by '#':" << std::endl;

	do {
		std::cin >> ch;//cin不读取空格,回车
		++count;
	} while (ch != '#');

	std::cout << "You entered " << count << " characters (not counting spaces)." << std::endl;
}

#include <iostream>

int main()
{
	const size_t max_num_characters{ 1'000 };
	char string[max_num_characters];

	std::cout << "Please enter a string: ";
	std::cin.getline(string, max_num_characters);

	// Count the number of characters
	size_t count{};
	for (; count < max_num_characters && string[count] != '\0'; ++count) {}

	// Print out the characters in reverse order
	for (size_t i = 1; i <= count; ++i)
	{
		std::cout << string[count - i];
	}
	std::cout << std::endl;
}
#include <iostream>

int main()
{
	const size_t max_num_characters{ 1'000 };
	char string[max_num_characters];

	std::cout << "Please enter a string: ";
	std::cin.getline(string, max_num_characters);

	// Count the number of characters
	size_t count{};
	while (count < max_num_characters && string[count] != '\0')
		++count;

	// Reverse the characters of the string entered by the user
	for (size_t i = 0; i < count / 2; ++i)
	{
		char temp = string[i];
		string[i] = string[count - i - 1];
		string[count - i - 1] = temp;
	}

	// Print out all characters, one by one
	for (size_t i = 0; i < count; ++i)
	{
		std::cout << string[i];
	}
	std::cout << std::endl;
}
//输出1到1000之间不能被7整除的所有整数,每列显示10个数字
#include <iostream>
#include <iomanip>
#include <vector>

int main()
{
	std::vector<unsigned> values;
	// Add element values 1 to bound
	for (unsigned i{ 1 }; i <= 1000; ++i)
		values.push_back(i);

	size_t count{};                              // Number of output values
	size_t perline{ 10 };                          // Number output perline                 
	for (auto value : values)
	{
		if (value % 7 == 0) continue;
		std::cout << std::setw(6) << value;
		if (++count % perline == 0) std::cout << "\n";
	}
	std::cout << std::endl;
}

//  Generate 93 Fibonacci numbers stored in an array.
// 93 was not an arbitrary choice for the number  of Fibonacci numbers.
// Fibonacci number grow fairly rapidly.
// 93 is the most that are possible with type unsigned long long.

#include <iostream>
#include <array>

int main()
{
	const size_t n{ 93 };
	std::array<unsigned long long, n> fib;
	fib[0] = fib[1] = 1UL;
	for (size_t i{ 2 }; i < n; ++i)
		fib[i] = fib[i - 1] + fib[i - 2];

	std::cout << "The first " << n << " Fibonacci numbers are:\n";
	for (auto number : fib)
	{
		std::cout << number << std::endl;
	}
}


 

《Beginning C++17》-学习笔记-Chapter 01-Basic Ideas 书名:Beginning C++17 - From Novice to Professional 作者:Ivor Horton, Peter Van Weert 笔记: Blocks can be placed inside other blocks—this concept is called nesting. Blocks can be nested, one within anothe... 阅读详情

相关推荐

《Beginning C++17》-学习笔记-Chapter 07-Working with Strings

#include &lt;iostream&gt; #include &lt;string&gt;//This header of the C++ Standard Library defines the std::string type /*Type string is a compound type, which is a type that’s a composite of severa...

CodingIsFun 536

the size of an array must be greater than zero

  Keil默认情况下,不允许出现长度为0的数组,例如char name[0];。   解决方法是使用gnu模式:Options for target -> C/C++ -> Misc Control -> input "--gnu"。

健身房 3731

相衬成像介绍

相衬成像介绍

qq_41981768的博客 2913

长度大小为零的数组(柔性数组、可变数组)

柔性数组(Arrays of Length Zero)是GNU/GCC在C/C++标准下扩展而引出的概念,其主要应用于构造可变长结构体中,嵌入式领域中一般被用于解析不定长数据包情境下。长度大小为0的数组这种定义是GNU/GCC扩展下引出的新特性,C/C++在C99标准下也对其进行了扩展支持,二者定义可能稍有不同。GNU/GCC下柔性数组定义char flag;int state;有些编译器并不认可这种定义方式,编译会报错提示数组长度必须大于0取而代之需要采用以下定义,定义一个长度未知的数组。

qiushui984620的博客 1829

UNITY3D万人同屏,Dots万人同屏解决方案_类萌宠宠之战

UNITY3D弹幕游戏开发,万人同屏解决方案

6472

一体化伺服电机与施耐德PLC TM241CEC24T在Canopen协议下的应用

一.硬件组成 软件组成:施耐德SoMachineV4.3二.○1.打开SoMachineV4.3,点击“新建项目”○2.点击“空白项目”○3.项目命名○4.点击“创建项目” 三. 点击“Logic Builder” 四. ○1.右击项目”PMM_CANOPEN_ST”添加设备○2.点击”LogicController”选择PLC型号TM241CEC24T/U○3.点击“添加设备” 五. ○1.右击CAN_1,添加设备○2.选择“CANopen Perfomance”○3.点击“添加设备”

m0_46512607的博客 2520

Value *** is outside of valid range for type java.lang.Integer

类型转换异常

龙城之家的博客 3863

WGS-84 ECEF ENU 坐标系学习记录

地球坐标系固定在地球上而随地球一起在空间做公转和自转运动,因此地球上任一固定点在地球坐标系的坐标就不会由于地球旋转而变化。地心地固直角坐标系和大地坐标系都属于这种坐标系。 一、 几种坐标系 地心地固直角坐标系(ECEF)坐标系 其原点为地球的质心,x轴延伸通过本初子午线(0度经度)和赤道(0deglatitude)的交点。 z轴延伸通过的北极(即,与地球旋转轴重合)。 y轴完成右手坐标系,穿...

YYshuangshuang的博客 1万+

keil中编译遇到错误“error #94-D the size of an array must be greater than zero”解决方法

这一期,我们来看一个在keil中编译时候遇到定义数组元素个数为0时候遇到的一个错误。

OMGMac的博客 1469

Microsemi Libero系列教程(一)——Libero开发环境介绍、下载、安装与注册

前言 相比与Xilinx和Altera在国内的市场,Microsemi的FPGA在国内应用很少很少,网上几乎没有详细的教程,刚开始使用时,遇到了各种问题,自己也走了不少弯路。本系列教程以Libero V11.8.2.4,SmartFusion系列A2F200M3F FPGA芯片为例,将详细介绍Libero SoC软件的基本使用,及使用过程中遇到一些问题的解决方法。 Libero 简介 关于Lib...

whik1194的博客 3万+

华为OD机试双机位C卷:采购订单 (Py/Java/C/C++/Js/Go)

华为OD机试双机位C卷 采购订单,提供C语言、Java、C++、Python、Go、JavaScript源码实现,并提供完整思路讲解,并提供在线OJ模拟做题。华为OD机试真题【采购订单】

qq_45776114的博客 3534

c语言sizeof报错,关于C中sizeof(class)用法引发的错误

当我在C中编译我的项目时,MSVC抛出以下错误:error #94: the size of an array must be greater than zero在执行sizeof时,在以下行中抛出错误:if (sizeof (MyNamespace::MyClass) == 60)因此定义了MyClass:class MyClass: public ParentClass{public:MyCl...

weixin_39743824的博客 1063

Ego Planner规划算法(上)——Ego Planner流程介绍

本系列文章用于学习记录Ego-Planner规划算法的相关内容,本系列文章是在在Fast Planner规划算法系列文章的基础上,展开对Ego Planner的相关介绍,主要包括Ego Planner算法流程和程序框架两部分,主要学习资料是深蓝学院的移动机器人运动规划课程

慕羽★的博客 1万+

c语言 多文件 连接错误,C中多文件中遇到的一些问题

最近在研究MSP430单片机的编程,开发环境是IAR for430.昨天调了一个程序,一直没有搞懂怎么出错的,知道今天才解决。总结下经验我的初衷是想定义一个全局数组,在main.c外的aa.h中声明了一个数组为 intaa[4];然后在aa.c文件中对数组赋初值。之后在main.c中调用数组aa某些元素的值。结果死活都调不通。错误类型如下:Error[Pe094]: the size of an ...

weixin_32848231的博客 2203

视觉SLAM十四讲slambook2示例代码所有依赖库的编译安装教程(VTK、OpenCV3、ceres、Sophus、g2o、Eigen、Pangolin、googletest等)

这是2021年的最后一篇博客~ 新年快乐! 0 准备工作   首先需要先安装cmake编译器: sudo apt-get install cmake   以及,将十四讲的示例代码克隆下来(十四讲的源码地址点击这里): git clone --recursive https://github.com/gaoxiang12/slambook2.git   由于里面的3rdparty文件夹内所有内容都来自于其他github仓库,所以需要加上--recursive参数,不然克隆下来的内容不完整。   如果你.

zeeq的博客 7839

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

【C++】《C++ 17 入门经典》读书笔记 07----数组的替代品之一: std::array 容器

介绍 C++17 中的数组替代品之一: std::array<T, N>容器。

风语留痕 659

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

【C++】《C++ 17 入门经典》读书笔记 08----数组的替代品之二: std::vector 容器

介绍 C++17 中数组的替代品: std::vector 容器。

风语留痕 488

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

《C++ Without Fear》学习笔记

书名:C++ Without Fear A Beginner’s Guide That Makes You Feel Smart 作者:Brian Overland 阅读时间:2018/10/6-2018/10/20 书摘+书评: An important rule of good programming style is that variables should usually...

CodingIsFun 832

《Beginning C++17》-学习笔记-Chapter 11-Defining Your Own Data Types

Every object of a given class incorporates the same combination of things, specifically, the set of data values as member variables of the class that characterize an object and the set of operations a...

CodingIsFun 667

《Beginning C++17》-学习笔记-Chapter 04-Making Decisions

There are only two possible bool values, true and false. True and false are keywords and are literals of type bool. They are sometimes called Boolean literals. #include &lt;iostream&gt; int main() ...

CodingIsFun 491

《Beginning C++17》-学习笔记-Chapter 09-Functions Templates

// Using a function template #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; template&lt;typename T&gt; T larger(T a, T b); // Function template prototype // a speciali...

CodingIsFun 456

《Beginning C++17》-学习笔记-Chapter 08-Defining Functions

/*A function with a return type other than void must return a value of the type specified in the function header. The only exception to this rule is the main() function, where reaching the closing bra...

CodingIsFun 456

《Beginning C++17》-学习笔记-Chapter 10-Program Files and Preprocessing Directives

#include "..\Power.h" /*including the file called Power.h located in the folder that includes the foler that includes this file.*/ Each source file, along with the contents of all the header files ...

CodingIsFun 424
上一篇: 《The Passionate Programmer》书摘
下一篇: 《Beginning C++17》-学习笔记-Chapter 06-Pointers and References
CodingIsFun
博客等级 码龄8年 37粉丝 240原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值