How to use STL array in C++

3 Answers

0 votes
#include <iostream> 
#include <array> 

int main() {
    const unsigned int ARRAY_SIZE = 5;

    using MyArray = std::array<int, ARRAY_SIZE>;
    MyArray arr = { 1, 5, 7, 9, 3 };

    for (unsigned int i = 0; i < ARRAY_SIZE; i++) {
        std::cout << arr[i] << " ";
    }
    
    std::cout << "\n";
    
    std::cout << arr.at(2) << "\n";   
    std::cout << arr.at(4); 
}




/*
run:

1 5 7 9 3 
7
3

*/

 



answered Feb 23, 2023 by avibootz
0 votes
#include <iostream> 
#include <array> 

int main() {
    const unsigned int ARRAY_SIZE = 5;

    std::array<int, ARRAY_SIZE> arr;
    arr.fill(-1);

    for (auto iter = arr.begin(); iter != arr.end(); iter++) {
            std::cout << *iter << " ";
    }
}




/*
run:

-1 -1 -1 -1 -1 

*/

 



answered Feb 23, 2023 by avibootz
0 votes
#include <iostream> 
#include <array> 

int main() {
    const unsigned int ARRAY_SIZE = 5;
    std::array<int, ARRAY_SIZE> a = {0, 1, 2, 3, 4};
    std::array<int, ARRAY_SIZE> b = {5, 6, 7, 8, 9};
    
    a.swap(b);

    for (auto& val : a) {
        std::cout << val << " ";
    }
    
    std::cout << "\n";
    
    for (auto& val : b) {
        std::cout << val << " ";
    }
}




/*
run:

5 6 7 8 9 
0 1 2 3 4 

*/

 



answered Feb 23, 2023 by avibootz

Related questions

1 answer 117 views
1 answer 119 views
1 answer 165 views
...