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;
}