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

Asked

Viewed 1,173 times

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?

1 answer

1

Matrix with Std:vector

To create a matrix with std::vector we have to make a std::vector within another, and to travel 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";
}

Matrix with Std:array

If it’s with std::array the initialization is already a little different, as well as the 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 a fixed size array that corresponds to doing something like array[10], which cannot change, whereas std::vector can receive more elements dynamically using the function push_back, thus:

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

Or remove using the function pop_back:

v.pop_back(); //remove o ultimo 15 adicionado

Browser other questions tagged

You are not signed in. Login or sign up in order to post.