Programing

find 메소드를 사용한 후 std :: map을 업데이트하는 방법은 무엇입니까?

lottogame 2020. 10. 10. 09:29
반응형

find 메소드를 사용한 후 std :: map을 업데이트하는 방법은 무엇입니까?


메서드를 std::map사용한 후 키 값을 업데이트 하는 find방법은 무엇입니까?

다음과 같은지도 및 반복기 선언이 있습니다.

map <char, int> m1;
map <char, int>::iterator m1_it;
typedef pair <char, int> count_pair;

나는 캐릭터의 발생 횟수를 저장하기 위해 맵을 사용하고 있습니다.

Visual C ++ 2010을 사용하고 있습니다.


std::map::find찾은 요소 (또는 end()요소를 찾을 수없는 경우)에 대한 반복기를 반환합니다 . 그래서 오랫동안 같이 mapconst를하지, 당신은 반복자가 가리키는 요소를 수정할 수 있습니다 :

std::map<char, int> m;
m.insert(std::make_pair('c', 0));  // c is for cookie

std::map<char, int>::iterator it = m.find('c'); 
if (it != m.end())
    it->second = 42;

연산자 []를 사용합니다.

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

따라서이 기술을 사용하면 스트림에서 모든 문자를 읽고 세는 것이 정말 쉬워집니다.

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

std::map::at멤버 함수 를 사용할 수 있으며 키 k로 식별되는 요소의 매핑 된 값에 대한 참조를 반환합니다.

std::map<char,int> mymap = {
                               { 'a', 0 },
                               { 'b', 0 },
                           };

  mymap.at('a') = 10;
  mymap.at('b') = 20;

이렇게 할 수도 있습니다.

 std::map<char, int>::iterator it = m.find('c'); 
 if (it != m.end())
 (*it).second = 42;

이미 키를 알고있는 경우 다음을 사용하여 해당 키의 값을 직접 업데이트 할 수 있습니다. m[key] = new_value

다음은 도움이 될 수있는 샘플 코드입니다.

map<int, int> m;

for(int i=0; i<5; i++)
    m[i] = i;

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
//Output: 0 1 2 3 4

m[4] = 7;  //updating value at key 4 here

cout<<"\n"; //Change line

for(auto it=m.begin(); it!=m.end(); it++)
    cout<<it->second<<" ";
// Output: 0 1 2 3 7    

다음과 같이 값을 업데이트 할 수 있습니다.

   auto itr = m.find('ch'); 
     if (itr != m.end()){
           (*itr).second = 98;
     }

참고 URL : https://stackoverflow.com/questions/4527686/how-to-update-stdmap-after-using-the-find-method

반응형