profile-img
์ง€๋ฐ์ด์˜ ํ‹ฐ์Šคํ† ๋ฆฌ
images/slide-image

์šฐ์„  ํ—ค๋”์— #include <iterator> ๋„ฃ๋Š”๊ฑฐ๋ฅผ ๊นŒ๋จน์ง€ ๋ง์ž!

 

ostream_iterator๋Š” ์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ ๋ฐ˜๋ณต์ž๋กœ, ํƒ€์ž… ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์›์†Œ์˜ ํƒ€์ž…์„ ๋ฐ›๋Š” ํด๋ž˜์Šค ํ…œํ”Œ๋ฆฟ์ž…๋‹ˆ๋‹ค. ์ƒ์„ฑ์ž๋Š” ์ถœ๋ ฅ ์ŠคํŠธ๋ฆผ๊ณผ ์ด ์ŠคํŠธ๋ฆผ์˜ ์›์†Œ ๋๋งˆ๋‹ค ๋ถ™์ผ string ํƒ€์ž…์˜ ๊ตฌ๋ถ„์ž๋ฅผ ์ธ์ˆ˜๋กœ ๋ฐ›์Šต๋‹ˆ๋‹ค. ostream_iterator ํด๋ž˜์Šค๋Š” ์ŠคํŠธ๋ฆผ์— ์›์†Œ๋ฅผ ์“ธ ๋•Œ operator<<๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

- Used to output data to an output stream 

ostream_iterator<Tyoe> out(ostream&);

 

์˜ˆ์‹œ:

#include <iterator>
...
ostream_iterator<char> screen1(cout);
copy(v.begin(), v.end(), screen1);
	//will output the contents of v

 

 

1. ostream iterator ์˜ delimiter (์ถœ๋ ฅ ๋ฐ˜๋ณต์ž์˜ ๊ตฌ๋ถ„์ž)

ostream_iterator<Type> out(ostream&, char* deLimit);

deLimit์ด๋ผ๋Š” ๊ตฌ๋ถ„์ž๋ฅผ ํ†ตํ•ด char๋‹จ์œ„๋กœ ์ชผ๊ฐœ์„œ ์ถœ๋ ฅํ•  ์ˆ˜ ์žˆ์Œ

 

์˜ˆ์‹œ:

ostream iterator<int> screen2(cout, " ");
copy(v.begin(), v.end(), screen2);
	// will output the contents of v
	// seperated by a space

 

2. range-based FOR loop

vector<int> aVector = {1, 2, 3, 4, 5};
for (int i : aVector)
	cout << i << " ";

- less prone to errors : ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜๋Š” out-of-bonds ์ ‘๊ทผ์„ ๋ฐฉ์ง€ ํ•˜๊ธฐ๋•Œ๋ฌธ์— ์˜ค๋ฅ˜ ๋ฐœ์ƒ๋ฅ ์ด ์ ์Œ 

- Does not use a counter variable : ์ธ๋ฑ์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ „ํ†ต์ ์ธ for loop์™€ ๋‹ฌ๋ฆฌ ์ปจํ…Œ์ด๋„ˆ์˜ ์š”์†Œ๋ฅผ ์ง์ ‘ ์‚ฌ์šฉ.  ๋ฐ˜๋ณต ๋ณ€์ˆ˜๋ฅผ ๋”ฐ๋กœ ์„ ์–ธํ•˜๊ฑฐ๋‚˜ ์—…๋ฐ์ดํŠธํ•  ํ•„์š”๊ฐ€ ์—†์Œ 

- Does not use a subscript operator : ๋ฐฐ์—ด์ ‘๊ทผ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•˜์ง€์•Š์Œ ! ์ปจํ…Œ์ด๋„ˆ์˜ ์š”์†Œ๋ฅผ ์ง์ ‘ ์ฐธ์กฐํ•จ

 

vector<string> aVector = {"First", "Middle", "Last"};
for(const string& i : aVector)
	cout << i << " ";

-> ์ฐธ์กฐ์‚ฌ์šฉํ•˜๊ธฐ !

 

3. AUTO !!

vector<int> aVector = {1, 2, 3, 4};

auto iter = aVector.begin();
auto iterEnd = aVector.end();

for(iter; iter != iterEnd; ++iter)
	cout << *iter;

 

์žฅ์  : initialization expression ์—์„œ ํ˜•์„ ์œ ์ถ”ํ•˜๊ฒŒ ํ•˜์—ฌ ์ฝ”๋“œ์˜ ๊ฐ€๋…์„ฑ์„ ๋†’์ž„. ex: (string) ์ผ์ผ€ํ•˜๋ฉด ๋„ˆ๋ฌด ๊ธธ๋‹ค..

๋‹จ์  : ๋ณ€์ˆ˜์˜ ํƒ€์ž…์ด ๋ช…ํ™•ํ•˜์ง€์•Š๊ฑฐ๋‚˜ ์ถ”๋ก ์ด ๋ณต์žกํ•  ๊ฒฝ์šฐ ์˜คํžˆ๋ ค ๊ฐ€๋…์„ฑ์„ ํ•ด์น  ์ˆ˜ ์žˆ์Œ ! 

 

 

 

๋ ! 

ostream๊ฒ๋‚˜ ์–ด๋ ต๋„ค.. ๋จผ์†Œ๋ฆฐ์ง€ ๋ชจ๋ฅด๊ฒ ๋‹ค ; /Mar 29 2024

'เซฎโ‚หถแต” แต• แต”หถโ‚Žแƒโ™ก/coding' Related Articles +