map_统计出现次数_temp_three_means

//

01 通过关键字计数 value1存在,value2++ 不存在,创建新的字值对( value1,1 ) 
    
    eg.
        mp[ s ]++;

02 先判断是否存在 存在则++ 不存在则新建

    eg.
        it=mp.find( s );
        if( it!=mp.end() )  it->second++;
        else                mp.insert( { s,1 } );

03 先插入 通过插入返回的迭代器判断是否存在 存在则++ 不存在则新建

    eg.
        pair< map< string,int >::iterator,bool > it;
        pit=mp.insert( { s,1 } );           // is "->" not "."
        if( pit.second==false ) pit.first->second++;

// eg.01
#include<bits/stdc++.h>
using namespace std;

map< string,int > mp;
map< string,int >::iterator it;

int main()
{
    string s;
    int n,i;
    
    while( cin>>n )
    {
    	cin.get();
		mp.clear();
		
		while( n-- ) { getline( cin,s ); mp[ s ]++; }
		
        for( it=mp.begin();it!=mp.end();++it )
            cout<<it->first<<' '<<it->second<<endl;
    }
    return 0;
}

// eg.02
#include<bits/stdc++.h>
using namespace std;

map< string,int > mp;
map< string,int >::iterator it;

int main()
{
    string s; int n,i;

    while( cin>>n )
    {
        cin.get(); mp.clear();

        while( n-- )
        {
            getline( cin,s );
            
            it=mp.find( s );
            if( it!=mp.end() )  it->second++;
            else                mp.insert( { s,1 } );
        }

        for( it=mp.begin();it!=mp.end();++it )
            cout<<it->first<<' '<<it->second<<endl;
    }
    return 0;
}

// eg.03
#include<bits/stdc++.h>
using namespace std;

map< string,int > mp;
map< string,int >::iterator it;
pair< map< string,int >::iterator,bool > pit;

int main()
{
    string s; int n,i;

    while( cin>>n )
    {
        cin.get(); mp.clear();

        while( n-- )
        {
            getline( cin,s );

            pit=mp.insert( { s,1 } );           // is "->" not "."
            if( pit.second==false ) pit.first->second++;
        }
        for( it=mp.begin();it!=mp.end();++it )
            cout<<it->first<<' '<<it->second<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/123616716