21xrx.com
2025-03-27 17:00:10 Thursday
文章检索 我的文章 写文章
C++ 插入函数源代码
2023-07-04 22:23:40 深夜i     --     --
C++ 插入函数 源代码

C++插入函数是一种在视觉上更改或修改数据结构的方法。它被广泛应用于各种编程语言中,包括C++语言。C++语言中,插入函数的实现是基于各种数据结构之一的。

以下是C++插入函数的源代码:

#include<iostream>
#define MAX 10
using namespace std;
class DynamicArray{
  int *array;
  int size;
  int capacity;
public:
  DynamicArray(){
    size = 0;
    capacity = MAX;
    array = new int[capacity];
  }
  //function to insert element
  void insert(int item){
    //checking if size is equal to capacity
    //if yes, then resize the array
    if (size == capacity) {
      int *temp = new int[2 * capacity];
      //Copy the contents of the array to the temporary array
      for(int i=0; i<capacity; i++){
        temp[i] = array[i];
      }
      //Delete the contents of the original array
      delete[] array;
      array = temp;
      capacity = capacity * 2;
    }
    array[size] = item;
    size++;
  }
  //function to display the elements in the array
  void display(){
    for (int i=0; i<size; i++)
    {
      cout << array[i] << " ";
    }
    cout << endl;
  }
};
//Driver code
int main()
{
  DynamicArray test;
  test.insert(1);
  test.insert(2);
  test.insert(3);
  test.insert(4);
  test.display();
  test.insert(5);
  test.insert(6);
  test.display();
  return 0;
}

这个例子使用一个动态数组来存储数据,并且在需要的时候自动扩大其容量。使用插入函数,可以将新元素添加到数组中。在本例中,我们首先创建了一个大小为10的数组,并使用insert()函数将4个元素添加到数组中。然后,我们添加两个额外的元素,并显示数组中所有的元素。

插入函数在C++编程中非常有用。它可以用于处理各种数据结构,其中包括数组、链表、堆、栈等等。使用插入函数,开发人员可以轻松地添加、删除或排序数据结构中的元素。这些函数广泛应用于不同的应用程序,并且在编写高效的算法时非常有用。

  
  

评论区