Chef and Arrays

c-plus-plus

#1
#include <iostream>
#include <vector>
#include <string>


int main() {

//Read in number of test cases
int tc = 0;
std::cin >> tc;

//Decrement test cases
while(tc--) {
    
    //Read in number of elements in array
    int n = 0;
    std::cin >> n;
    
    //Declare two arrays of size n
    int a[n];
    int b[n];
    
    //Populate array with values
    for (int i = 0; i < n; ++i) {
        std::cin >> a[i];
    }
    for (int i = 0; i < n; ++i) {
        std::cin >> b[i];
    }
    
    std::vector<int> newInts(n);
    
    for (int i = 0; i < n; ++i) {
        if (a[i] > b[i]) {
            int appended = std::stoi(std::to_string(a[i]) + std::to_string(b[i]));
            newInts.push_back(appended);
        } else if (b[i] > a[i]) {
            int appended = std::stoi(std::to_string(b[i]) + std::to_string(a[i]));
            newInts.push_back(appended);
        } else {
            int appended = std::stoi(std::to_string(a[i]) + std::to_string(b[i]));
            newInts.push_back(appended);
        }
    }
        
        //Print vector contents
        for (int i = 0; i < newInts.size(); ++i) {
             std::cout << newInts[i] << std::endl;
        }


}
return 0;

}

Link: https://www.codechef.com/ENMA2019/problems/NUTLOOP
The problem with my code is that it is also printing out trailing zeroes. Can anyone help me fix this? It prints out
0
0
0
0
0
31
22
31
44
55
The values I want come after the trailing zeroes but I don’t know how they are there in the first place. Please help :slight_smile:


#2

This creates a vector of size n.

Add values at back of vector.

Basically, you have created a vector of size n. And after appending n times your vector size is n.

Either remove that n.
Or newInts[i]=appended;