C++ : Vector 관련 함수

Se0ng_1l·2022년 12월 7일
0

코딩기법

목록 보기
6/6
post-thumbnail

Vector관련 문법

1. 최대값 최소값 찾기, min_element, max_element

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


int main(){
    vector<int> v = {1,2,3,4,5,6,7,8};
    cout << *max_element(v.begin(), v.end()) << endl;
    cout << max_element(v.begin(), v.end()) - v.begin() << endl; // 인덱스를 리턴
    cout << *min_element(v.begin(), v.end()) << endl;
    cout << min_element(v.begin(), v.end()) - v.begin() << endl; // 인덱스를 리턴
}

2. 원하는 값 찾기, find()

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> v = {1,2,3,4,5,6,7,8};

    cout << find(v.begin(), v.end(), 4) - v.begin() << endl;
    // 인덱스를 리턴
    // 결과 : 3

    // 있는지 없는지 유무확인
    if(find(v.begin(), v.end(), 9) == v.end())
    {
        cout << "못찾겠다 꾀꼬리!" << endl;
    }

    if(find(v.begin(), v.end(), 8) != v.end())
    {
        cout << "찾아버렸다 !!!" << endl;
    }
}

3. 원하는 값 삭제, erase(), remove()

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    vector<int> v = {1,2,3,4,5,6};

    cout << "init size : " << v.size() << " init capacity : " << v.capacity() << endl;
    // 1. erase(), 3을 삭제하고 싶다.
    v.erase(v.begin() + 2);
    cout << endl << "erase 결과 : ";
    for(const auto &m : v)
    {
        cout << m << ' ';
    }
    cout << endl << "size : " << v.size() << " capacity : " << v.capacity() << endl;
    // 2. remove(), 5를 삭제하고 싶다.

    remove(v.begin(), v.end(), 5);
    cout << endl << "remove 결과 : ";
    for(const auto &m : v)
    {
        cout << m << ' ';
    }
    cout << endl << "size : " << v.size() << " capacity : " << v.capacity() << endl;
    // 결과 :
    //init size : 6 init capacity : 6
	//erase 결과 : 1 2 4 5 6 
	//size : 5 capacity : 6
	//remove 결과 : 1 2 4 6 6
	//size : 5 capacity : 6
}

❓remove로 삭제했는데 왜 5가 6으로 대체된건가요?

그 전에 erase의 작동방식에 대해 알아보자
erase로 삭제한 경우 원소의 삭제함과 동시에 vectorsize가 줄어든다.

하지만,
remove로 삭제하는경우 삭제될 값의 크기 만큼 뒤에 있는 값들을 앞으로 땡겨 온 다음, 남은 공간은 이전에 있었던 값들로 채운다.
따라서 5에 위치에 뒤에 있는 6의 값을 땡겨왔다.
그 다음 남은 공간을 가장 뒤에 있었던 원소의 값 6으로 대신 채운것이다.

ex)
만약 다수의 원소를 삭제한다면 어떨까?
1,2,3,4,4,4,4,5,6에서 4를 삭제한다고 해보자
=> 1 2 3 5 6 4 4 5 6 ( ⭕️ )
=> 1 2 3 5 6 6 6 6 6 ( ❌ )

단점.
erase의 경우 중복 데이터를 없애기 위해 여러번 수행해야 할 수 있다.( 데이터가 띄엄띄엄 있는 경우)
remove의 경우 중복데이터는 처리할 수 있지만 size가 줄어들지 않는다.

❗️ 다수의 중복된 원소를 삭제하면서 크기도 줄이기

erase와 remove둘다 사용하기

remove는 땡겨온 원소 중 마지막 원소의 다음 위치의 반복자를 리턴한다.
1,2,3,4,4,4,4,5,6 경우라면,
1 2 3 5 6 4 4 5 6 처음 만나는 4의 위치를 리턴하는 것이다.

#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

int main()
{
    vector<int> v = {1, 4, 4, 2, 4, 3, 4, 4, 5, 6};

    v.erase(remove(v.begin(), v.end(), 4), v.end());
    cout << "결과 : ";
    for(const auto &m : v)
    {
        cout << m << ' ';
    }
    cout << endl << "size : " << v.size() << " capacity : " << v.capacity() << endl;
    // 결과 : 1 2 3 5 6
    // size : 5 capacity : 10
}

4. 중복된 원소 배제하기, unique()

unique()는 중복되지 않은 원소들을 채울때 사용한다.
중복된 값들은 배열의 뒤로 보낸다.
unique()의 반환값은 뒤로 보낸 중복된 원소 중 가장 먼저 뒤로 보낸 원소의 위치를 반환한다.
따라서 erase()를 사용하면 중복값을 제거할 수 있다.
❗️조건 :
연속된 값으로 정렬된 배열에만 사용할 수 있다.
따라서, sort()를 사용해 배열을 정렬하고 사용해야한다.

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(1);
    v.push_back(3);
    v.push_back(2);
    v.push_back(4);
    v.push_back(3);
    
    sort(v.begin(), v.end());
    v.erase(unique(v.begin(), v.end()),v.end());
    for(int i = 0; i < v.size(); i++){
        cout << v[i] << ' ';
    }
	// 결과 : 1 2 3 4
}

5. 순서를 거꾸로 바꾸기, reverse()

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v(5);
    v = {1, 2, 3, 4, 5};

    for(int i = 0; i < v.size(); i++)
        cout << v[i] <<' ';
    cout << endl;

    reverse(v.begin(), v.end());
    for(int i = 0; i < v.size(); i++)
        cout << v[i] <<' ';
    
    // 결과 : 1 2 3 4 5
           : 5 4 3 2 1
}
profile
치타가 되고 싶은 취준생

0개의 댓글