How to mount an array with std :: array and std :: vector in C ++ 11?

0

How to mount an array with std :: array and std :: vector in C ++ 11? What is the difference between the two architectures? How to scan this array with C ++ 11?

    
asked by anonymous 15.07.2017 / 03:59

1 answer

0

Array with std :: vector

To create an array with std::vector we have to make a std::vector inside another, and to go we can use the for : that c ++ 11 provides:

//matrix de 2 x 2 com std::vector 
std::vector<std::vector<int>> matriz = { {7, 5}, {16, 8}};

for(std::vector<int> linha: matriz) { //percorrer cada linha
    for (int linha : vetor){ //percorrer cada numero dentro da linha
        std::cout << numero << ' '; 
    }
    std::cout<<"\n";
}

Array with std :: array

If it is with std::array the initialization already gets a bit different, just like for , although it is the same principle:

//matrix de 3 x 2 com std::array 
std::array<std::array<int, 3> , 2> matriz2 = {{ {{2 , 5, 3}} , {{1, 4, 8}} }};

for (auto& linha : matriz2){
    for (auto& numero : linha){
        std::cout << numero << ' ';
    }

    std::cout<<"\n";
}

Example to test on ideone

Differences

The biggest difference between the two is that std::array is an array of fixed length and that corresponds to doing something like array[10] , which can not change, whereas std::vector can receive more elements dynamically using the function push_back , like this:

std::vector<int> v = {7, 5, 16, 8};
v.push_back(15); //adiciona outro elemento a este vetor

Or remove using the pop_back function:

v.pop_back(); //remove o ultimo 15 adicionado
    
15.07.2017 / 12:10