C++

[C++] vector 정리

yisj 2023. 9. 16. 10:36

반복자의 사용

for (auto p = v.begin(); p != v.end(); ++p)
	cout << *p << endl;

 

i번째 요소 삭제

v.erase(v.begin() + i);

 

벡터 정렬하기

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

class Person
{
private:
    string name;
    int age;
public:
    Person(string n, int a)
    {
        name = n;
        age = a;
    }
    string get_name() { return name; }
    int get_age() { return age; }
    void print() {
        cout << name << " " << age << endl;
    }
};

bool compare(Person &p, Person &q)
{
    return p.get_age() < q.get_age();
}

int main()
{
    vector<Person> list;

    list.push_back(Person{"Kim", 30});
    list.push_back(Person{"Park", 22});
    list.push_back(Person{"Lee", 26});

    sort(list.begin(), list.end(), compare);

    for(auto e : list)
        e.print();
    
    return 0;
}

'C++' 카테고리의 다른 글

[C++] g++ 사용법 및 g++ 옵션들  (1) 2023.11.22
Windows에 gcc 설치하기  (0) 2023.11.08
[C++] 라이브러리 별 함수 정리  (0) 2023.09.16
[C++] 연산자 정리  (0) 2023.09.16
[C++] 생성자 정리  (0) 2023.09.16