题目链接:单词问题

找一个字符串里的所有单词,重复的只输出一次。关于map函数key值是字符串的问题一直比较含糊...

挣扎了一番,大概是,map的key值是char型数组的时候,标记的是地址,于是有map[char *, int]mp;然而..这就并没有什么卵用了吧..

然后...如果是string的话...怎么能让map认识这个字符串呢..string.resize(num);的作用应该就是在字符串末尾加上了结束符...然后...每次增加一个字符的时候..如果已经遇上了结束符...是不可以的...程序就崩溃了....这个时候应该结束符位置之后的地址都属于超出数组范围了...于是字符数组越界..这就跟地址分配有关了...

该题直接暴力先把所有的字符串存起来...每次输出的时候依次查找是不是前面是不是有过也是可以得...(就是有点蠢...)

神奇的resize函数...是时候学一发C++语法了..

附代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <map>
using namespace std;

string str;
string temp;
map<string, int>mp;

int main() {
    while(cin >> str) {
        int len = str.length();
        temp = "";
        temp.resize(200);
        int cnt = 0;
        mp.clear();

        for (int i=0; i<len; ++i) {
            //if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {
            if (isalpha(str[i])) { // 和上一行等价...就是体验一下有钱人的生活...
                temp[cnt++] = str[i];
            }
            else if (cnt != 0) {
                temp.resize(cnt); // 没有该行 map无法正确标记该字符串
                if (mp[temp] == 0) {
                    cout << temp << endl;
                    mp[temp]++;
                }

                cnt = 0;
                //temp = "";
               temp.resize(200); // 没有该行会崩溃
            }
            if (i == len-1 && cnt != 0) {
               temp.resize(cnt);
               if (mp[temp] == 0) {
                    cout << temp << endl;
               }
            }
        }
    }
    return 0;
}

  

posted on 2016-04-07 11:14  小小八  阅读(313)  评论(0编辑  收藏  举报