阅读量:4
在C++中,可以使用以下方法动态地为变量赋值:
- 使用
new关键字为数组分配内存并动态赋值:
#include
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;
}
- 使用
std::vector容器动态赋值:
#include
#include
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容器动态地为数组分配内存并赋值。这样可以根据用户输入的大小和元素值来创建和初始化变量。
以上就是关于“c++定义变量 怎样动态赋值”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm