PrevUpHomeNext

day-19: c++ array, function, lambda


c++ array

c++ raw array. c++ array is a continuous area of a list of raid values in the c++ memory.

Syntax:

the_value_type the_array_name[the_array_size] = {value1, value2, ...};	// (1)
the_value_type the_array_name[the_array_size];	// (2)
the_value_type the_array_name[] = {value1, value2, ...};	// (3)

For example:

int xzz[4] = {2, 3, 5, 2};

the_value_type is int, the_array_name is xzz, the_array_size is 4, which means the array xzz has four int values. These four elements are initialized with 2, 3, 5, 2.

The stored positions of the four elements in memory are continuous, which means they are stored one after another tightly.

For (3), the_array_size is not specified, because the size can be deduced from its value initilizer list.

#include <iostream>

int main()
{
	int arr4[] = {2,3,9,5,7,23}; // array size is auto-deduced as 6
	for (int x: arr4)
	{
		std::cout << "x is " << x << ' ';
	}
	std::cout << std::endl;
}

output:

2 3 9 5 7 23

c++ function

c++ function is similar to the method of a class, just the function does not belong to a class. c++ example:

float fn_xx(float x, float y)
{
	return x + y;
}

// Use the function:
auto result = fn_xx(1.2f, 2.1f);

Put c++ function in a namespace:

namespace my_space
{

float fzzz(const float x, const float y)
{
	return x+y;
}

}

// Use the function:
auto result = my_space::fzzz(2.1f, 1.2f);

c++ lambda

General speaking, lambda is advanced function. Function is the function of value. Lambda is the function of function.

Syntax:

auto the_lambda_name = [<<capture-list>>] (<<arg-list>>)
{
	<<statement-list>;
};

For example:

#include <iostream>

auto fn = [] (float x)
{
	std::cout << "Receive: " << x << std::endl;
	return x*x;
};

int main()
{
	int y = fn(2.1f);
	std::cout << "Got: " << y << std::endl;
}

Output:

Receive: 2.1
Got: 4.41

fn is a lambda object. It is an object of a class.







Written on Dec 06, 2024

Back to index

Index

cpp/c++

c++ std::exception:

std::cout.write(err.data(), err.size());

std::cout << std::endl;

caught:

  ===================================
  #  The c++ programming language.  #
  #                                 #
  #  Join c++ Discord: yZcauUAUyC   #
  #  Deck                           #
  ===================================

Home: cppfx.xyz

K


PrevUpHomeNext