๐Ÿ’ฏ์ฑŒ๋ฆฐ์ง€๋ฐ˜ ๋ณต์Šต ๋…ธํŠธ(4)

์นผ๋“ ๊ฐœ๊ตฌ๋ฆฌยท2025๋…„ 2์›” 12์ผ
0
post-thumbnail

์œ ๋‹ˆํฌ ๊ฐ’ ๊ตฌํ•˜๊ธฐ

unique๋Š” ์—ฐ์†๋œ ์ค‘๋ณต ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜์—ฌ (๋ ์œ„์น˜) iterator๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜์ด๋‹ค. ์ด ํ•จ์ˆ˜๋Š” ์ •๋ ฌ์ด ํ•„์ˆ˜์ด๋‹ค.

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

int main() {
    vector<int> v = {1, 4, 4, 2, 2, 2, 5, 1};
    sort(v.begin(), v.end()); // ์ •๋ ฌ ํ•„์ˆ˜! {1, 1, 2, 2, 2, 4, 4, 5} ์ด๋ ‡๊ฒŒ ๋˜๊ฒ ์ฃ ?

    auto newEnd = unique(v.begin(), v.end()); // ์ด๊ฑด ์•„๋ž˜์—์„œ ์ž์„ธํžˆ ์„ค๋ช…
    v.erase(newEnd, v.end()); // ์ค‘๋ณต๋˜๋Š” ๊ตฌ๊ฐ„ ์ „๋ถ€ ์‚ญ์ œ!

    for (int x : v) cout << x << " ";
}

์ดํ•ฉ ๊ตฌํ•˜๊ธฐ

accumulate๋Š” ์ดํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฐ ์‚ฌ์šฉ๋œ๋‹ค

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

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

   int sum = accumulate(v.begin(), v.end(), 0);
   cout << "์ดํ•ฉ: " << sum << endl;
}

4๋ฒˆ์งธ ์ธ์ž๋ฅผ ์ถ”๊ฐ€๋กœ ์„ธํŒ…ํ•˜๋ฉด ๋‚ด๊ฐ€ ์›ํ•˜๋Š” ์—ฐ์‚ฐ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์ด ๊ณฑ์„ ์•Œ๊ณ  ์‹ถ๋‹คํ•˜๋ฉด multiplies ๋ฅผ ์จ์ฃผ๋ฉด ๋œ๋‹ค

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

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

		// ๊ณฑ์…ˆ์ด๋‹ˆ ์ดˆ๊ธฐ๊ฐ’์€ 1๋กœ ์‹œ์ž‘ํ•ด์•ผ๊ฒ ์ฃ ?!
    int product = accumulate(v.begin(), v.end(), 1, multiplies<int>());
    cout << "์ด๊ณฑ: " << product << endl;
}

๋žŒ๋‹ค ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉ์ž ์ •์˜ ๊ณ„์‚ฐ์„ ํ•  ์ˆ˜ ์žˆ๋‹ค.. ์˜ˆ๋ฅผ ๋“ค์–ด, ์ดํ•ฉ์„ ๊ตฌํ•  ๋•Œ ๊ฐ ์›์†Œ๋งˆ๋‹ค 2์”ฉ์„ ๋” ํ•ด์ค˜์•ผ๋œ๋‹ค๊ณ  ํ•˜๋ฉด

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

int main() {
   vector<int> v = {1, 2, 3, 4};
   int sum = accumulate(v.begin(), v.end(), 0, [](int a, int b) {
       return a + b + 2;
   });
   cout << "์ดํ•ฉ: " << sum << endl; // 10์ด ์•„๋‹ˆ๋ผ 18์ด ์ถœ๋ ฅ
}

๋น ๋ฅธ ์ด์ง„ ํƒ์ƒ‰


lower_bound / upper_bound๋Š” ์ •๋ ฌ๋œ ๊ตฌ๊ฐ„์—์„œ์˜ ์ด์ง„ ํƒ์ƒ‰์„ ๊น”๋”ํ•˜๊ฒŒ ์ œ๊ณตํ•ด์ค€๋‹ค

profile
๋ฉ”ํƒ€์ญ์ด

0๊ฐœ์˜ ๋Œ“๊ธ€