温馨提示×

c++定义变量 怎样动态赋值

c++
小樊
94
2024-12-05 01:50:18
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用以下方法动态地为变量赋值:

  1. 使用new关键字为数组分配内存并动态赋值:
#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "Enter the size of the array: ";
    cin >> n;

    int* arr = new int[n]; // 分配内存

    cout << "Enter elements of the array: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i]; // 动态赋值
    }

    cout << "Elements of the array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    delete[] arr; // 释放内存
    return 0;
}
  1. 使用std::vector容器动态赋值:
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cout << "Enter the size of the array: ";
    cin >> n;

    vector<int> arr(n); // 分配内存并初始化为0

    cout << "Enter elements of the array: ";
    for (int i = 0; i < n; i++) {
        cin >> arr[i]; // 动态赋值
    }

    cout << "Elements of the array: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

在这两个示例中,我们分别使用new关键字和std::vector容器动态地为数组分配内存并赋值。这样可以根据用户输入的大小和元素值来创建和初始化变量。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++如何定义变量

0