Vector-Sort, iterator

b4failrise ㅣ 2018. 6. 28. 22:50

N 개의 integer가 주어졌다. N개의 integer를 정렬하고 정렬된 순서로 출력하라.

N개의 integer들을 vector에 저장하라. vector들은 크기를 변경할 수 있는 배열을 표현하는 순차 컨테이너(sequence containers)이다.


Declaration:

vector<int>v;    (creates an empty vector of integers)


Size:

int size = v.size();


Pushing an integer into a vector:

v.push_back(x);    (where x is an integer. The size increases by 1 after this.)


Popping the last element from the vector:

v.pop_back();    (After this the size decreases by 1)


Sorting a vector:

sort(v.begin, v.end());    (Will sort all the elements in the vector)




Input Format

The first line of the input contains  where  is the number of integers. The next line contains  integers.
Constraints

, where  is the  integer in the vector.

Output Format

Print the integers in the sorted order one by one in a single line followed by a space.

Sample Input

5
1 6 10 8 4

Sample Output

1 4 6 8 10


We access the elements of a vector the same way that we access the characters

in a string: through their position in the vector. For example, we can use a range

for to process all the elements in a vector:


vector<int> v{1,2,3,4,5,6,7,8,9};

for (auto &i : v) // for each element in v (note: i is a reference)

i *= i; // square the element value

for (auto i : v) // for each element in v

cout << i << " "; // print the element

cout << endl;




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <algorithm>    //for sort function
#include <iterator>
using namespace std;
 
//sol1)
int main()
{
    int n, num;
    cin >> n;
    vector<int> v;    // Empty Vector
    for (int i = 0; i < n; i++)    // appends an element for each loop
    {
        cin >> num;
        v.push_back(num);
    }
    sort(v.begin(), v.end());        // v.begin() : Return iterator to beginning
    for (int i : v)
        cout << i << " ";
    cout << endl;
}
cs



1
2
3
4
5
6
7
8
9
10
//sol2)
int main()
{
    vector<int> v;
    int n;
    cin >> n;
    copy_n(istream_iterator<int>(cin), n, back_insert_iterator<vector<int>>(v));
    sort(v.begin(), v.end());
    copy(v.begin(), v.end(), ostream_iterator<int>(cout" "));
}
cs


'객체 지향 설계' 카테고리의 다른 글

사용자 정의 함수를 이용한 sort함수  (0) 2019.04.13
Union  (0) 2018.06.29
Operator Overloading, Operator Conversions  (0) 2018.06.28
Class  (0) 2018.06.27
string Streams  (0) 2018.06.26