Search code examples
c++vectorpush-back

Pushback elements of other arrays


I created two arrays A and B, the array C should store the first elements of A and B. Ex : A={1,2,3}, B={4,5,6}, C must be {1,4,2,5,3,6}. My program doesn't show anything after the input of my arrays. This is my loop :

for(int i(0);i<3;i++){
        C.push_back(A[i]);
        C.push_back(B[i]);
}

for(int i(0);i<6;i++){
        std::cout << C[i] << " ";
}

Solution

  • Try this:

    int main()
    {
        std::vector<int> A = {1,2,3};
        std::vector<int> B = {4,5,6};
        std::vector<int> C;
        for (int i(0); i < 3; i++)
        {
            C.push_back(A[i]);
            C.push_back(B[i]);
        }
    
        for (int i(0); i < 6; i++)
        {
            std::cout << C[i] << " ";
        }
    
        return 0;
    }
    

    Or you can change it to:

    int main()
    {
        std::vector<int> A(3);
        std::vector<int> B(3);
        for (int i = 0; i < 3; ++i)
        {
            std::cin >> A[i];
        }
        for (int i = 0; i < 3; ++i)
        {
            std::cin >> B[i];
        }
        std::vector<int> C;
        for (int i(0); i < 3; i++)
        {
            C.push_back(A[i]);
            C.push_back(B[i]);
        }
    
        for (int i(0); i < 6; i++) 
        {
            std::cout << C[i] << " ";
        }
    
        return 0;
    }