C++ vector 를 정렬하거나, 역순으로 돌리고자 할 때

 

 

작은 것을 맨 앞으로, 순차적으로 정렬하고자 할 때

sort(a.begin(), a.end());

 

 

 

역순으로(큰 것을 맨 앞으로) 정렬하고자 할 때

begin -> rbegin 으로 변경해주면 된다.

 

sort(a.rbegin(), a.rend());

 

 

정렬은 하지 않고,

단순히 현재 순서를 역순으로 변경하고자 할 때

reverse(a.begin(), a.end());

 

 

 

 

vector의 begin(), end() 는 시작과 끝을 가르키는 것으로

sort, reverse 에서 파라미터로 입력되는 부분은 범위를 지칭한다.

 

만약에 한 vector a 가 10개의 구성요소로 이뤄져있을 때,

맨 처음부터 절반만 sort 하고 싶은 경우

sort(a.begin(), a.begin()+5) 이렇게 범위를 지정해주면 된다.

 

#include <algorithm>
#include <vector>


int test(vector<int> a)
{
	// a 가 { 1, 3, 2 } 인 경우,

	sort(a.begin(), a.end());
	// 위 로직후, a 의 결과
	// { 1, 2, 3 }


	sort(a.rbegin(), a.rend());
	// 위 로직후, a 의 결과
	// { 3, 2, 1 }


	reverse(a.begin(), a.end());
	// 위 로직후, a 의 결과
	// { 1, 2, 3 }
    
}

 

두 자연수의 곱 = 최대공약수 x 최소공배수

 

최대공약수, 최소공배수 둘 다 구해야하는 상황에서

위 공식을 이용하면,

더 빠르게 결과를 얻을 수 있다.

 

vector<int> solution(int n, int m) {
    vector<int> answer;
    
    // 임의의 두 자연수가 주어졌을 때,
    // 작은 수, 큰 수를 일단 구분한다
    int small, big;
    
    if( n > m ){
        big = n;
        small = m;
    }else{
        big = m;
        small = n;
    }
    
    
    // 최대공약수를 구한다
    // 두 자연수의 공통공약수 1로 초기화
    int greatestCommonFactor = 1;
    
    // 최대공약수는 작은 수보다 클 수 없으므로
    // 작은 수 부터 2까지 loop로 살펴보면서,
    // 주어진 두 자연수를 나눴을 때 나머지가 없는 경우가 나타나면
    // 최대공약수를 찾은 것이고 loop 를 빠져나온다.
    for(int i=small ; i>=2 ; i--){
        if( small % i == 0 && big % i == 0){
            greatestCommonFactor = i;
            break;
        }
    }
    
    // 최소공배수르 구한다
    // 주어진 두 자연수의 곱에서 앞서 구한 최대공약수를 나눠주면 끝
    LeastCommonMultiple = small * big / greatestCommonFactor;



	// 답을 세팅해 준다
    answer.push_back(greatestCommonFactor);
    answer.push_back(LeastCommonMultiple);
    
    return answer;
}

 

 

 

 

최대공약수 없이, 최소공배수만 구해야 하는 경우는

vector<int> solution(int n, int m) {
    vector<int> answer;
    
    // 임의의 두 자연수가 주어졌을 때,
    // 작은 수, 큰 수를 일단 구분한다
    int small, big;
    
    if( n > m ){
        big = n;
        small = m;
    }else{
        big = m;
        small = n;
    }
    
    
    // 최소공배수
    // 주어진 두 자연수 중, 큰 수로 초기화
    int LeastCommonMultiple = big;
    
    // 큰 수의 배수를 살펴본다
    // 큰 수에서 (큰 수 * 작은 수) 까지 loop로 살펴보면 된다
    for( int j=1 ; j <= small ; j++){
        if( (big * j) % small == 0 ){
            LeastCommonMultiple = big * j;
            break;
        }
    }
    
    

	// 답을 세팅해 준다
    answer.push_back(greatestCommonFactor);
    answer.push_back(LeastCommonMultiple);
    
    return answer;
}

 

 

 

 

vector<int> test = { 1, 2, 3 };

 

위와 같이 값이 포함되도록 vector를 초기화 해주면,

vector test 에는 1,2,3 요소가 포함되게 된다.

위 vector 값을 빈 값으로 초기화가 필요한 경우가 있다.

 

그럴 때 사용하는 방법은

 

test.clear();

 

clear() 해주면 빈 값으로 초기화 된다.

 

 

vector 초기화가 필요한

2차원 행렬 vector 덧셈 로직 예시이다.

vector<vector<int>> sum_two_dimensional_vector(vector<vector<int>> arr1, vector<vector<int>> arr2) {
    vector<vector<int>> answer;

    vector<int> temp;
    int sum;

    for(int i=0 ; i < arr1.size() ; i++ ){
    	
        // 1차원 vector 간의 합을 임시로 저장하는 vector 변수 초기화
        temp.clear();
        
        // 1차원 vector 각 원소를 더한 값을, 임시 1차원 vector에 넣어줌
        for(int j=0 ; j < arr1[i].size() ; j++ ){
            sum = arr1[i][j] + arr2[i][j];
            temp.push_back(sum);
        }
        
        // 2차원 vector인 answer에 1차원 vector 넣어줌
        answer.push_back(temp);
    }


    return answer;
}

+ Recent posts