STL:map

STL:map(映射)  

主要操作



三种插入方式:

2.1.1insert方法插入pair对象:

enumMap.insert(pair<int, Cstring>(1,“One”));

2.1.2 insert方法插入value_type对象:

enumMap.insert(map<int,Cstring>::value_type (1, “One”));

2.1.3 数组方式插入值:

enumMap[1] = "One";

enumMap[2] = "Two";

......

这样非常直观,但存在一个性能的问题。插入2,先在enumMap中查找主键为2的项,没发现,然后将一个新的对象插入enumMap,键是2值是一个空字符串,插入完成后,将字符串赋为"Two";该方法会将每个值都赋为缺省值,然后再赋为显示的值,如果元素是类对象,则开销比较大。用前两种方法可以避免开销。



STL map2.2 查找并获取map中元素

2.2.1下标操作符给出了获得一个值的最简单方法:

CString tmp = enumMap[2];

但是,只有当map中有这个键的实例时才对,否则会自动插入一个实例,值为初始化值。

2.2.2我们可以使用find()count()方法来发现一个键是否存在

查找map中是否包含某个关键字条目用find()方法,传入的参数是要查找的key,在这里需要提到的是begin()和end()两个成员,分别代表map对象中第一个条目和最后一个条目,这两个数据的类型是iterator.

int nFindKey = 2; //要查找的Key

UDT_MAP_INT_CSTRING::iterator it=enumMap.find(nFindKey);

//定义一个条目变量(实际是指针)

if(it == enumMap.end())

{

       cout<<"没找到"<<endl;

}

else

{

       cout<<"找到了"<<endl;

}

通过map对象的方法获取的iterator数据类型是一个std::pair对象,包括两个数据。

iterator->first 关键字(key)

iterator->second 存储的数据(value)



STL map2.3 map删除元素

2.3.1移除某个map中某个条目用erase()

该成员方法的定义如下:

1.iterator erase(iterator it); //通过一个条目对象删除

2.iterator erase(iterator first, iterator last); //删除一个范围

3.size_type erase(const Key& key); //通过关键字删除

补充:

1.使用删除之前的迭代器定位下一个元素。STL建议的使用方式

map<string,int>::iterator   it;

for(it=mapTest.begin();it!=mapTest.end();)
{
       mapTest.erase(it++);
}

2. erase() 成员函数返回下一个元素的迭代器

for(it=mapTest.begin();it!=mapTest.end();)
{
       it=mapTest.erase(it);
}

2.3.2清除所有的元素clear()

clear()就相当于 enumMap.erase(enumMap.begin(),enumMap.end());


STL map2.4 mapswap的用法

map中的swap不是一个容器中的元素交换,而是两个容器交换;

For example:

#include <map>

#include <iostream>

using namespace std;

int main( )

{

map <int, int> m1, m2, m3;

map <int, int>::iterator m1_Iter;

m1.insert ( pair <int, int> ( 1,10 ) );

m1.insert ( pair <int, int> ( 2,20 ) );

m1.insert ( pair <int, int> ( 3,30 ) );

m2.insert ( pair <int, int> ( 10,100 ) );

m2.insert ( pair <int, int> ( 20,200 ) );

m3.insert ( pair <int, int> ( 30,300 ) );

cout << "The original map m1is:";

for ( m1_Iter = m1.begin( ); m1_Iter !=m1.end( ); m1_Iter++ )

cout << " " <<m1_Iter->second;

cout << "." <<endl;

// This is the member function versionof swap

//m2 is said to be the argument map; m1the target map

m1.swap( m2 );

cout << "After swapping with m2, map m1 is:";

for ( m1_Iter = m1.begin( ); m1_Iter !=m1.end( ); m1_Iter++ )

cout << " " <<m1_Iter -> second;

cout << "." <<endl;

cout << "After swapping with m2, map m2 is:";

for ( m1_Iter = m2.begin( ); m1_Iter !=m2.end( ); m1_Iter++ )

cout << " " <<m1_Iter -> second;

cout << "." <<endl;

// This is the specialized templateversion of swap

swap( m1, m3 );

cout << "After swapping with m3, map m1 is:";

for ( m1_Iter = m1.begin( ); m1_Iter !=m1.end( ); m1_Iter++ )

cout << " " <<m1_Iter -> second;

cout << "." <<endl;

}


STL map2.5 mapsort问题

Map中的元素是自动按key升序排序,所以不能对map用sort函数:

For example:

#include <map>

#include <iostream>

using namespace std;

int main( )

{

map <int, int> m1;

map <int, int>::iterator m1_Iter;

m1.insert ( pair <int, int> ( 1,20 ) );

m1.insert ( pair <int, int> ( 4,40 ) );

m1.insert ( pair <int, int> ( 3,60 ) );

m1.insert ( pair <int, int> ( 2,50 ) );

m1.insert ( pair <int, int> ( 6,40 ) );

m1.insert ( pair <int, int> ( 7,30 ) );

cout << "The original map m1is:"<<endl;

for ( m1_Iter = m1.begin( ); m1_Iter !=m1.end( ); m1_Iter++ )

cout <<m1_Iter->first<<" "<<m1_Iter->second<<endl;

}

The original map m1 is:

1 20

2 50

3 60

4 40

6 40

7 30


操作总览




 begin()         返回指向map头部的迭代器
   clear()         删除所有元素
   count()         返回指定元素出现的次数
   empty()         如果map为空则返回true
   end()           返回指向map末尾的迭代器
   equal_range()   返回特殊条目的迭代器对
   erase()         删除一个元素
   find()          查找一个元素
   get_allocator() 返回map的配置器
   insert()        插入元素
   key_comp()      返回比较元素key的函数
   lower_bound()   返回键值>=给定元素的第一个位置
   max_size()      返回可以容纳的最大元素个数
   rbegin()        返回一个指向map尾部的逆向迭代器
   rend()          返回一个指向map头部的逆向迭代器
   size()          返回map中元素的个数
   swap()          交换两个map
   upper_bound()   返回键值>给定元素的第一个位置
   value_comp()    返回比较元素value的函数



简单例题:反片语(ANANAGRAMS,UVa 156)



//紫书P113

Most crossword puzzle fans are usedto anagrams--groups of words with the same letters in differentorders--for example OPTS, SPOT, STOP, POTS and POST. Some words however do nothave this attribute, no matter how you rearrange their letters, you cannot formanother word. Such words are called ananagrams, an example is QUIZ.

Obviously such definitions depend on the domain within which we areworking; you might think that ATHENE is an ananagram, whereas any chemist wouldquickly produce ETHANE. One possible domain would be the entire Englishlanguage, but this could lead to some problems. One could restrict the domainto, say, Music, in which case SCALE becomes a relative ananagram (LACESis not in the same domain) but NOTE is not since it can produce TONE.

Write a program that will read in the dictionary of a restricted domainand determine the relative ananagrams. Note that single letter words are, ipsofacto, relative ananagrams since they cannot be ``rearranged'' at all. Thedictionary will contain no more than 1000 words.

Input

Input will consist of a series of lines. No line will be more than 80characters long, but may contain any number of words. Words consist of up to 20upper and/or lower case letters, and will not be broken across lines. Spacesmay appear freely around words, and at least one space separates multiple wordson the same line. Note that words that contain the same letters but ofdiffering case are considered to be anagrams of each other, thus tIeD and EdiTare anagrams. The file will be terminated by a line consisting of asingle #.

Output

Output will consist of a series of lines. Each line will consist of asingle word that is a relative ananagram in the input dictionary. Words must beoutput in lexicographic (case-sensitive) order. There will always be at leastone relative ananagram.

Sample input

ladder came tape soonleader acme RIDE lone Dreis peat

ScAlE orbeyeRides dealerNotE derail LaCeSdrIed

noel dire Disk maceRob dries

#

Sample output

Disk

NotE

derail

drIed

eye

ladder

soon

题意:把每个单词全部转化成小写字母,对每个单词,看它的字母重排后得到的单词在所有输入的单词中是否出现过,若没有出现,就输出原单词。所有要输出的单词按字典序排列输出。



#include<iostream>
#include<string>
//#include<cctype>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;

map<string,int> cnt;
vector<string> words;

string repr(const string& s)
{
    string ans=s;
    for(int i=0;i<ans.length();i++)
    {
        ans[i]=tolower(ans[i]);
    }
    sort(ans.begin(),ans.end());
    return ans;
}

int main()
{
    int n=0;
    string s;
    while(cin>>s)
    {
        if(s[0]=='#')
            break;
        words.push_back(s);
        string r=repr(s);
        if(!cnt.count(r))
            cnt[r]=0;
        cnt[r]++;
    }
    vector<string> ans;
    for(int i=0;i<words.size();i++)
        if(cnt[repr(words[i])]==1)
            ans.push_back(words[i]);
    sort(ans.begin(),ans.end());
    for(int i=0;i<ans.size();i++)
        cout<<ans[i]<<"\n";
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_42390424/article/details/81051255