🧼C, C++/흑마법

배열의 차원을 구하는 방법 C++ (강화버전)

Mawile 2021. 10. 12.
728x90

안녕하세요!!

이번에는 저번에 배열의 차원의 찻수를 구하는 방법에 관하여 포스팅했습니다.

 

몇시간 더 삽질하면서, "벡터에 클래스가 들어와도 정상적으로 작동시킬수 없을까?"라는 생각이 들어서 강화버전을 준비했습니다.

https://mawile.tistory.com/206

 

배열의 차원을 구하는 방법 C++

우리는 흔히 배열의 크기를 구하고는 합니다. 예를들어서 이런식으로 말이죠.. int main() { int arr[5]; int size = sizeof(arr) / sizeof(arr[0]); } 하지만 ... 만약 아래 코드와 같은 5차원 배열이 존재할때,..

mawile.tistory.com

이번에는 저번에 만들었던 로직을 살짝수정하여 좀더 강력하게, 클래스가 와도 정상작동되게 수정했죠...훗..

 

#include <iostream>
#include <vector>
#include <type_traits>

template<class dataType, class originType>
constexpr inline auto __getDimension_Vector_s(dataType const& Vector, std::size_t size) -> std::size_t{
	auto CopiedVector{Vector};
	if constexpr(!std::is_same_v<decltype(CopiedVector), originType>){
		if(CopiedVector.empty()) CopiedVector.push_back({});
		return __getDimension_Vector_s<decltype(CopiedVector[0]), originType>(CopiedVector[0], ++size);
	}
	return --size;
}

template<class dataType, class originType>
constexpr inline auto __getDimension_Vector_s(dataType const& Vector) -> std::size_t{
	if constexpr(!std::is_same_v<dataType, originType>){
		auto CopiedVector{Vector};
		if(CopiedVector.empty()) CopiedVector.push_back({});
		return __getDimension_Vector_s<dataType, originType>(CopiedVector, 1);
	}
	return 1;
}

template<class originType>
constexpr inline auto getDimension_Vector_s(auto const& Vector) -> std::size_t{
	return __getDimension_Vector_s<decltype(Vector), originType>(Vector);
}

class cClass{};

int main() {
	std::vector<std::vector<std::vector<std::vector<int>>>> vec; // int
	std::vector<std::vector<cClass>> new_vec; // cClass
	
	std::cout << getDimension_Vector_s<int>(vec) << '\n'; //Ok
    std::cout << getDimension_Vector_s<cClass>(new_vec) << '\n'; //Ok
}

 

와우~~!!!!

저번에는 불가능했던 클래스를 넣어도 정상작동하였습니다.

 

이제 수정된 로직에 대하여 설명드리겠습니다.

 

수정된 로직

(수정 전)

파라미터로 넘겨받은 인자의 타입이 클래스인지 판별

 

(수정 후)

템플릿으로 넘겨받은 실제 벡터에 담겨지는 데이터의 타입과 현재 벡터의 타입을 비교하여

두 타입이 다른지 판별

 

 

궁금한점이 있으신 분들은 댓글로 질문주세요!

그럼 안녕~~~!!


728x90

'🧼C, C++ > 흑마법' 카테고리의 다른 글

배열의 차원을 구하는 방법 C++  (0) 2021.10.11
가변인자 프린트함수 ( c++23 )  (0) 2021.06.23

댓글