SW/C++

C++ : std::array : 개념, 장점, 단점, 필요성, 활용성, 예제, 구현

얇은생각 2020. 5. 3. 07:30
반응형

C++ : std::array : 개념, 장점, 단점, 필요성, 활용성, 예제, 구현

 

std::array

요소 수를 기억하지 않습니다. 단순히 C 스타일 배열을 추상화한 것이라 생각하면 좋습니다. 요소 수를 기억하지 못하므로 std::array가 아쉬울 수 있습니다. 아마 std::algorithm을 쓸 수 있고, 반복자를 쓸 수 있어서 나온 것일까요. 현재 사이즈를 접근할 필요가 없고, 고정형 크기의 배열이 필요하다면 선택지로 사용할 수 있는 컨테이너라는 생각이 들었습니다.

다만 프로젝트에서 그러한 경우가 그렇게 많지 않을 것으로 생각이 되었는데, 만약 그러한 상황이어도 굳이, 익숙하지 않은 array를 꺼내지 않아도 얼마든지 다른 방법으로도 충분히 해결 가능합니다. 이러한 컨테이너가 있다는 것을 기억해두고 좋은 기회가 오면 활용해보는 것도 좋을 것 같습니다.

 

#include <array>

int main()
{
    std::array<int, 5> n = { 1, 2, 3, 4, 5 };

    std::cout << n[2] << std::endl;

    return 0;
}

 

#include <string>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
 
int main()
{
    // construction uses aggregate initialization
    std::array<int, 3> a1{ {1,2,3} };  // double-braces required
    std::array<int, 3> a2 = {1, 2, 3}; // except after =
    std::array<std::string, 2> a3 = { {std::string("a"), "b"} };
 
    // container operations are supported
    std::sort(a1.begin(), a1.end());
    std::reverse_copy(a2.begin(), a2.end(), std::ostream_iterator<int>(std::cout, " "));
 
    // ranged for loop is supported
    for(auto& s: a3)
        std::cout << s << ' ';
}

 

#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int, 5> n;

    //taking values of elements from user
    for(int i = 0; i < n.size() ; i++)
    {
	cout << "Enter value of n[" << i << "]"<< endl;
    	cin >> n[i];
    }

    /* printing the values of elements of array */
    for (int j = 0; j < n.size(); j++ )
    {
        cout << "n[" << j << "] = " << n[j] << endl;
    }
    return 0;
}
반응형