ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • stl::map에서 update
    Computer/Programming 2011. 6. 29. 10:45

    stl::map에 에서 이미 존재하는 항목을 update하기 위해서는 다음과 같이 사용한다.

    #include <stdio.h>
    #include <map>
    void main() {
    	std::map<int, int> test1;
    	test1[0] = 1;
    	test1[1] = 2;
    	test1[1] = 3;
    	for (auto it = test1.begin(); it != test1.end(); it++) {
    		printf("%d %d\n", it->first, it->second);
    	}
    }
    

    배열에 값을 할당하듯 사용하면
    해당되는 key 값이 없으면 map에 새로 추가되고,
    해당되는 key 값이 없으면 map에 있는 해당 항목 값이 변경된다.

    그런데 stl::map 구조를 pointer로 선언했을 때는 배열 사용하듯 할 수가 없고 값의 변경을 위한 함수가 따로 존재하지 않는다.
    이 때는 다음 과 같이 해당 항목을 find 함수로 찾아서 값을 변경해준다.
    #include <stdio.h>
    #include <map>
    void main() {
    	std::map<int, int>* test = new std::map<int, int>();
    	test->insert(std::pair<int, int> (0,1));
    	test->insert(std::pair<int, int> (1,2));
    	test->find(1)->second = 3;
    	// test->find(2)->second = 4;
    	for (auto it = test->begin(); it != test->end(); it++) {
    		printf("%d %d\n", it->first, it->second);
    	}
    }



Designed by Tistory.