따르릉

내가 볼려구.. 계속해서 추가할 예정이다! 

 

sqrt

#include <iostream>
#include <cmath>

int main() {
    double x = 25.0;
    double root = sqrt(x);

    std::cout << "The square root of " << x << " is " << root << std::endl;

    return 0;
}

 

정렬

 

#include <algorithm>
#include <array>

using namespace std;
//기본은 오름차순. 3번째 인자에 넣는 함수로 정렬 기준을 바꿀 수 있다. 

//역순 
bool compare(int a, int b) {
    return a > b;
}

//array에는 다음과 같이 사용할 수 있다.
//void sort(RandomIt first, RandomIt last);
//void sort(RandomIt first, RandomIt last, Compare comp);

array<int, 5> arr = {4, 2, 1, 5, 3};
sort(arr.begin(), arr.end());


std::vector<int> v = {4, 2, 1, 5, 3};
std::sort(v.begin(), v.end(), compare);

 

 

 

vector 자르기 

#include <iostream>
#include <vector>

using namespace std;

int main(){
	vector <int> myVector={1,2,3,4,5,6};
    
    auto it_start = next(v.begin(), 2); // 인덱스 2부터 시작, 타입은 vector<int>::iterator
	auto it_end = next(v.begin(), 5);   // 인덱스 5 이전까지, 값 6의 주소
    
    vector <int> subVector(it_start, it_end); // {3,4,5}
}

string 자르기

#include <string>

string str ="123456";

int startIndex=1;
int endIndex=4;

str=str.subString(startIndex,endIndex); // "2,3,4,5"

 

reverse 

 

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    std::reverse(v.begin(), v.end()); // v를 역순으로 뒤집음
    
    //단순 역순으로 출력할 때
    for (auto it = v.rbegin(); it != v.rend(); ++it) {
        std::cout << *it << " ";
    }
    return 0;
}

'코딩테스트 > C++' 카테고리의 다른 글

find 사용법  (0) 2023.03.15
C++ 문자/문자열을 숫자로 바꾸기  (0) 2023.03.13
약수 구하기  (0) 2023.03.10

+ Recent posts