๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’Ž/C++

[C++] map iterator(๋ฐ˜๋ณต์ž) ํ™œ์šฉ

by dar0m! 2020. 3. 23.

map์˜ ์›์†Œ๋Š” pair ๊ฐ์ฒด๋กœ ์ €์žฅ๋˜๋ฉฐ

pair ๊ฐ์ฒด์˜ first ๋ฉค๋ฒ„ ๋ณ€์ˆ˜๋Š” key๋กœ second ๋ฉค๋ฒ„ ๋ณ€์ˆ˜๋Š” value์ด๋‹ค.

์˜ˆ์ œ

#include <iostream>
#include <map>
using namespace std;
map<int, int> m;	// map ์„ ์–ธ
int main() {

	m[10] = 4;
	m[8] = 9;
	m[100]++;

	map<int, int>::iterator iter;	// iterator ์„ ์–ธ

	for (iter = m.begin(); iter != m.end(); iter++) {
		printf("์ฃผ์†Œ๊ฐ’: %d ", iter);
		printf("key: %d ", *iter);
		printf("key: %d value: %d\n", iter->first, iter->second);
	}

	map<int, int>::iterator iter2 = m.begin();	// iterator ์„ ์–ธ๊ณผ ๋™์‹œ์— ์ดˆ๊ธฐํ™”

	for (; iter2 != m.end(); iter2++)
		printf("%d %d %d\n", iter2, iter2->first, iter2->second);

	return 0;
}

์‹คํ–‰๊ฒฐ๊ณผ

  • key๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ๋˜์–ด ์ €์žฅ๋จ.
  • vector iterator ์ฒ˜๋Ÿผ iter[3] ๊ฐ™์ด ์ž„์˜์ ‘๊ทผ ์•ˆ ๋จ.

 

๋Œ€์•ˆ

for(auto it = m.begin(); it != m.end(); it++){
	printf("%d", *it);
}

c++11 ๋ถ€ํ„ฐ ์ง€์›ํ•˜๋Š” auto ๋ฅผ ์“ฐ๋ฉด ๊ฐ„๋‹จํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋Œ“๊ธ€