在c或c++中编写一段函数用来求线性表的长度
时间: 2024-04-29 18:22:06 浏览: 15
在 C 语言中,线性表通常使用数组来实现,因此可以通过计算数组的大小来求线性表的长度。可以编写以下函数:
```c
#include <stdio.h>
int length(int arr[]) {
// 计算数组的大小
int size = sizeof(arr);
// 计算数组中元素个数
int count = size / sizeof(arr[0]);
return count;
}
int main() {
// 定义一个数组
int arr[] = {1, 2, 3, 4, 5};
// 调用 length 函数求线性表长度
int len = length(arr);
printf("The length of the linear list is %d\n", len);
return 0;
}
```
在 C++ 中,线性表通常使用标准库中的容器来实现,如 `vector`、`list` 等,可以使用容器的 `size` 函数来求线性表的长度。例如:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
// 定义一个 vector
vector<int> v = {1, 2, 3, 4, 5};
// 求线性表长度
int len = v.size();
cout << "The length of the linear list is " << len << endl;
return 0;
}
```