c++vectorstd-pair

Is it possible to make array of pairs


I am new to c++ so I want to ask is it possible to make an array of pair in c++ just like we create a vector of pair.

int n;
 cin>>n;
 array < pair <int,int> >v[n];

I am trying to make array like this but not getting positive results.


Solution

  • It looks like you are trying to dynamically allocate an array of std::pair<int,int>. Prefer std::vector for such a task:

    #include <iostream>
    #include <utility>
    #include <vector>
    
    int n;
    
    std::cin >> n;
    
    std::vector<std::pair<int,int>> v{n};
    

    As to your original question, you can create arrays of std::pair<int,int>, either C-style arrays or std::arrays. However, you will need to know the size at compile-time:

    int n;
    
    std::cin >> n;
    
    
    //C-style arrays
    std::pair<int,int> a[n]; //this may work on some compilers, but is non-standard behaviour
    
    //std::arrays
    #include <array>
    
    std::array<std::pair<int,int>,n> a; //this will not compile at all, "n" must be known at compile-time