C 中的动态矢量创建

Dynamic vector creation in C++

本文关键字:创建 动态      更新时间:2023-10-16

我正在尝试创建一个x数量的向量。在运行时间内将确定X的数量。也就是说,如果用户说他们需要2个向量,我们会创建两个向量,如果他们说他们需要3个,我们会创建3个向量等。在C 中执行此操作的最佳方法是什么?创建后我该如何使用这些方法?

假设您是指std::vector,那么您问题的一种解决方案是使用向量的向量(无需双关语)。例如:

#include <iostream>
#include <vector>
int main()
{
    // Create a vector containing vectors of integers
    std::vector <std::vector<int>> v;
    int X = 2; // Say you want 2 vectors. You can read this from user.
    for(int i = 0; i < X; i++)
    {
        std::vector<int> n = {7, 5, 16, 8}; // or read them from user
        v.push_back(n);
    }
    // Iterate and print values of vector
    for(std::vector<int> n : v) 
    {
        for(int nn : n )
            std::cout << nn << 'n';
        std::cout << std::endl;
    }
}