BP-5-2 Array Type

Chapter 05 Compound Data Type - Constructed Type

2. Array Type

Array Type is a user-defined compound data type to describe a sequence of elements.

2.1 Single Dimensional Array

Single dimensional array can describes data structure called linear list.

  • Definition of Single Dimensional Array
<type-of-the-elements> <name-of-the-array> [<number-of-elements>];

Here type of elements is called base type, and it can be any type in C++, atomic or compound, but not void. Name of the array is an identifier which can represent the array. Number of elements is a integral constant expression, remember: constant.

typedef <type-of-the-elements> <alias-of-the-array-type> [<number-of-elements>];

The keyword typedef gives an alias to a certain kind of data, compound or atomic, and the we can refer to this type using alias and use it to define variables as we always do : <data-type> <variable-name>;.

Notice that in a C++ program, the length of an array is fixed and unchangeable.

  • Initialization for Variables in Single Dimensional Arrays

    When initializing an newly defined array, we use a pair of brace to include them, and the number of our initial value can’t exceed the length of the array. If we haven’t provided enough initial value, the other elements in the array will be initialized as 0.

    Moreover, we are allow to leave out the number of elements if we define an array whose length is exactly the number of initial values we give.

    Here are some examples:

    int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int b[10] = {1, 2, 3, 4}; //The other element execpt the first four will be initialized 
    int c[] = {1, 2, 3}; //The length of c[] is 3.
    
  • Manipulation for Single Dimensional Arrays

    • get item

      <array-name> [<index/subscript>];
      

      We can have access to an element of an array with its name and a subscript giving the elements index.

      Remember that the elements of an array is indexed from 0 and don’t exceed its maximum length.

    • element manipulation

      Manipulation for an element of an array is not on the same scale as manipulation for the array.

      As to the elements, you can do what you can do to a normal variable to an element of the array such as assignment, self-increase or self-decrease, using it as an operand and so on.

    • We should use iteration or loop to travel the array so that we could get access to each element.

    Arrays are not first class in C++ programs. They are discriminated, so if we want to do something to it, we must one element at a time.

  • How The Single Dimensional Array are Stored in The Memory

    Let us use the following definition as an example:

    int a[10];
    

    First, the memory will give the array ten rooms next to each other whose addresses is constant.

    Then, put each initial value in its corresponding room if there is one initial value.

    Moreover, we can get each room’s address using the following formula:

    <first-element-address> + <index> * sizeof(<base-data-type>)
    

    Having a good understanding of how an array stored will help me understand how to use the pointer to manipulate an array better.

  • How to Pass a Single Dimensional Array to a Function

    We usually need to pass the name of an array and its length of it to a function to manipulate it or refer to it.

    In the parameter list, the syntax for a single dimensional array is <base-type> <name>[].

    Notice that the array or any other compound data type is called by reference, which means the function calling it could have some side effects.

2.2 Single Dimensional Character Array - A Implementation for Strings

Each Character Array must end with \0, which marks the end of the string. The length of the string depends on the place of \0 and its maximum length is the length of the array minus one because the last character must be \0.

  • Definition of a Character Array
char s[10] = {'h', 'e', 'l', 'l', 'o', '\0'};
char s[10] = {"hello"};
char s[10] = "hello";
char s[] = "hello";
//The last three statements will add a '\0' in the end of the string by default.
  • Manipulation of a character array is just the same as regular arrays.
Useful Small Functions of Character Array
int strlen(char str[]){
    int i = 0;
    while (str[i] != '\0') i++;
    return i;
}
int str_to_int(char str[]){
    int n = 0;
    for (int i = 1; str[i] != '0'; i++)
        n = n*10 + (str[i] - '0');
    return n;
}
int find_substr(char str[], char sub_str[]){
    int len = strlen(str), sub_len = strlen(sub_str);
    for (int i = 0; i <= len - sub_len; i++) {
        int j = 0;
        while (j < sub_len && sub_str[j] == str[i + j]) j++;
        if (j == sub_len) return i;
    }
    return -1;
}
void reverse(char str[]) {
    int len = strlen(str);
    for (int i = 0, j = len - 1; i < j; i++, j--){
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}
2.3 Double Dimensional Array

Double dimensional array describes a kind of data structure that has rows and columns, such as a matrix. Each element of it can be fixed exactly with its row index and column index.

  • Definition of a Double Dimensional Array

    <element-type> <array-name> [<row-number>][<column-number>];
    //or
    typedef <element-type> <alias> [<row-number>][<column-number>];
    <alias> <array-name>;
    

    If we give a single dimensional array type an alias and use it as the base type to construct another single dimensional array, actually this array is double dimensional.

  • Initialization of a Double Dimensional Array

    Just observe the examples below, I’m sure you’ll find the rules and syntax.

    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    int a[2][3] = {1, 2, 3, 4, 5, 6};
    //the two statements above works the same
    int a[2][3] = {{1, 2}, {3, 4}};
    int a[2][3] = {1, 2, 3, 4};
    //the two statements above works differently
    //uninitialized elements will be assigned 0 by default
    int a[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    //the number of column can't be left out anyway while the number of rows can be left out.
    
  • Manipulation for Double Dimensional Array

    • get item

      <array-name> [row-index][column-index]
      
    • As is always the case, array in C++ is not first class, so any manipulation should be done element by element.

    • So if we want to travel a double dimensional array, we should use nested iteration.

  • Store of Double Dimensional Array

    It is just the same as the single dimensional array if we see it as a single dimensional array with its base type to be single dimensional array.

    If you understand the above, all nth dimensional arrays can be viewed as a special kind of single dimensional array.

  • Pass a Double Dimensional Array to a Function

    In the parameter list, a double dimensional array is described as <base-type> <array-name>[][column-number].

    We should leave out the number of rows as we preserve the number of columns.

    We can’t leave out the number of rows because the address of a[i][j] is computed by the following formula:

    addr(a[i][j]) = addr(a[1][1]) + i * number-of-columns + j
    //addr(a[1][1]) is stored in the name a.
    

    We must the number of columns to help get the item.

2.4 Application
  • Matrix Multiplication
#include <iostream>
using namespace std;
int main(){
    const int M = 2, N = 3, T = 4;
    int a[M][N], b[N][T], c[M][T];
    cout << "Please input matrix A(" << M << " * " << N << "): " << endl;
    for (int i = 0; i < M; i++)
        for (int j = 0; j < N; j++)
            cin >> a[i][j];
    cout << "Please input matrix B(" << N << " * " << T << "): " << endl;
    for (int i = 0; i < N; i++)
        for (int j = 0; j < T; j++)
            cin >> b[i][j];
    for (int i = 0; i < M; i++) {
        for (int j = 0; i < N; j++) {
            c[i][j] = 0;
            for (int k = 0; k < N; K++)
                c[i][j] += a[i][k] * b[k][j];
        }
    }
    cout << "The multiplication of matrix A and B is C(" << M << " * " << T << "):" << endl;
    for (int i = 0; i < M; i++) {
        for (int j = 0; j < T; j++)
            cout << c[i][j] << " ";
    	cout << endl;
    }
    return 0;
}
  • Josephus Problem
#include <iostream>
using namespace std;
const int N = 20, M = 5;

int main(){
    bool in_circle[N];
    int num_of_children_remained = N, index;
    for (index = 0; index <= N - 1; index++)
        in_circle[index] = true;
    index = N - 1;
    while (num_of_children_remained > 1) {
        int count = 0;
        while (count < M) {
            index = (index + 1) % N;
            if (in_circle[index]) 
                count++;
        }
        in_circle[index] = false;
        num_of_children_remained--;
    }
    for (index = 0; index < N; index++)
        if (in_circle[index]) break;
    cout << "The winner is No." << index << ". \n";
    return 0;
}
  • Selection Sort
void sel_sort(int x[], int n) {
    for (; n > 1; n--) {
    	int i_max = 0;
    	for (int i = 1; i < n; i++)
        	if (x[i] > x[i_max]) i_max = i;
        int temp = x[i_max];
        x[i_max] = x[n - 1];
        x[n - 1] = temp;
    }
}
  • Quick Sort
int split(int x[], int first, int last){
    int split_point = first, pivot = x[first];
    for (int unknown = first + 1; unknown <= last; unknown++)
        if (x[unknown] < pivot) {
            split_point++;
            int temp = x[split_point];
            x[split_point] = x[unknown];
            x[unknown] = temp;
        }
    x[first] = x[split_point];
    x[split_point] = pivot;
    return split_point;
}

void quick_sort(int x[], int first, int last) {
    if (first < last) {
        int split_point = split(x, first, last);
        quick_sort(x, first, split_point - 1);
        quick_sort(x, split_point + 1, last);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于BP神经网络的图像分割代码,该代码使用Python和PyTorch实现: ```python import torch import torch.nn as nn import torch.optim as optim import numpy as np import cv2 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(3, 10) # 输入层到隐层 self.fc2 = nn.Linear(10, 1) # 隐层到输出层 def forward(self, x): x = torch.sigmoid(self.fc1(x)) x = torch.sigmoid(self.fc2(x)) return x def train(net, criterion, optimizer, inputs, targets): optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() return loss def main(): # 读取图像并转换为numpy数组 img = cv2.imread("image.jpg") img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (64, 64)) img = np.array(img) / 255.0 # 定义网络结构、损失函数、优化器 net = Net() criterion = nn.MSELoss() optimizer = optim.SGD(net.parameters(), lr=0.1) # 准备训练数据 inputs = torch.from_numpy(img.reshape((64 * 64, 3)).astype(np.float32)) targets = torch.from_numpy(np.random.randint(0, 2, (64 * 64, 1))).float() # 开始训练 for i in range(10000): loss = train(net, criterion, optimizer, inputs, targets) if i % 1000 == 0: print("epoch: {}, loss: {}".format(i, loss)) # 对图像进行分割 with torch.no_grad(): outputs = net(inputs) outputs = outputs.numpy().reshape((64, 64)) outputs = (outputs >= 0.5).astype(np.uint8) * 255 # 显示结果 cv2.imshow("Image", img) cv2.imshow("Segmentation", outputs) cv2.waitKey(0) cv2.destroyAllWindows() if __name__ == "__main__": main() ``` 这个代码将一张图像划分为两个区域:背景和前景。该模型使用了一个简单的BP神经网络,将图像的RGB值作为输入,输出一个值表示该像素属于哪个区域。在训练过程中,使用随机的标签来训练模型,最终将模型应用于整张图像进行分割。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值