21xrx.com
2025-03-26 01:03:13 Wednesday
文章检索 我的文章 写文章
C++向量的源代码
2023-06-29 00:53:46 深夜i     10     0
C++ 向量 源代码

C++是一种流行的编程语言,用于创建复杂的计算机程序。在这种语言中,向量是一个允许您存储和访问多个值的容器。向量是一个强大的工具,因为它可以提供灵活性和可重用性。

以下是一个简单的C++向量类的源代码:

#include <iostream>
#include <vector>
using namespace std;
template<class T>
class Vector {
  private:
    T* arr;
    int capacity;
    int current;
  
  public:
    Vector() {
      arr = new T[1];
      capacity = 1;
      current = 0;
    }
    
    void push(T data) {
      if (current == capacity) {
        T* temp = new T[2 * capacity];
        for (int i = 0; i < capacity; i++) {
          temp[i] = arr[i];
        }
        delete[] arr;
        capacity *= 2;
        arr = temp;
      }
      arr[current] = data;
      current++;
    }
    
    void push(T data, int index) {
      if (index == capacity)
        push(data);
      else
        arr[index] = data;
    }
    
    void pop()
      current--;
    
    
    T& operator[](int index) {
      if (index >= current || index < 0)
        throw "Index out of bounds";
      return arr[index];
    }
    
    int size()
      return current;
    
    
    int getcapacity()
      return capacity;
    
    
    void print() {
      for (int i = 0; i < current; i++) {
        cout << arr[i] << " ";
      }
      cout << endl;
    }
};
int main() {
  Vector<int> v;
  v.push(1);
  v.push(2);
  v.push(3);
  v.push(4);
  v.push(5);
  v.push(6);
  v.push(7);
  v.push(8);
  v.push(9);
  v.push(10);
  v.push(11);
  v.push(12);
  v.push(13);
  
  cout << "Vector v: ";
  v.print();
  cout << "Vector size: " << v.size() << endl;
  cout << "Vector capacity: " << v.getcapacity() << endl;
  
  v.pop();
  cout << "Popped last element" << endl;
  
  cout << "Vector v: ";
  v.print();
  cout << "Vector size: " << v.size() << endl;
  cout << "Vector capacity: " << v.getcapacity() << endl;
  
  v.push(13, 3);
  cout << "Vector v after changing element at index 3 to 13: ";
  v.print();
  
  return 0;
}

该向量类使用动态内存分配,因此可以在运行时扩展向量的大小。它还支持插入和删除元素,以及访问指定索引处的元素。此外,作为一个模板类,它可以用于存储任何类型的数据(int,char,double等)。

  
  

评论区

请求出错了