poj-3096

66 篇文章 1 订阅
7 篇文章 0 订阅
//600K  0MS G++
#include <set>
#include <cstdio>
#include <string>
#include <cstring>

using namespace std;



struct classcomp {
    bool operator() (const char* lhs, const char* rhs) const {
        // if (lhs[0] == rhs[0] && lhs[1] == rhs[1]) {
        //     return 0;
        // } else {
        //     return 1;
        // }
        return lhs[0] == rhs[0] ? lhs[1] > rhs[1] : lhs[0] > rhs[0];
    }
};

typedef set<const char*, classcomp> Dset;

Dset dset;

typedef set<const char*, classcomp>::iterator DsetIt;
set<const char*, classcomp>::iterator it;

char checkSurprising(const string str) {
    if (str.length() <=2) {
        return 1;
    } else {
        for (int D = 1; D < str.length() - 1; D++) {
            for (DsetIt curIt = dset.begin(); curIt != dset.end(); curIt++) {
                delete [] (*curIt);
            }
            dset.clear();
            // printf("BEGIN\n");
            for (int i = 0; i <= str.length() - D -1; i++) {
                char * Dstr = new char[2];
                Dstr[0] = str[i];
                Dstr[1] = str[i+D];
                // printf("%c%c %d\n", Dstr[0], Dstr[1], (int)dset.size());
                if ((it = dset.find(Dstr)) != dset.end()) {
                    // printf("XX %c%c\n", (*it)[0], (*it)[1]);
                    return 0;
                } else {
                    dset.insert(Dstr);
                }
            }
        }
    }
    return 1;
}

int main() {
    char tmp[82];
    while(scanf("%s", tmp) != EOF) {
        if (!strcmp(tmp, "*")) {
            return 0;
        }
        string str = tmp;
        if (checkSurprising(str)) {
            printf("%s is surprising.\n", tmp);
        } else {
            printf("%s is NOT surprising.\n", tmp);
        }
    }
}

水题,但是因为生疏了STL set的用法,以及string浅拷贝的问题,还是出了些问题,这道题用来检验C++的知识还是不错的。

首先是忘了STL set怎么判断元素相等:

set中判断元素是否相等:
      if(!(A<B||B<A)),当A<B和B<A都为假时,它们相等。
然后就是循环中局部变量分配了:

一开始每次循环搞一个string, 然后做判断,insert进去,

后来发现个怪事,在某次循环对此string进行修改,会直接反应到已经存入set的string,刚开始时,还怀疑set难道不是拷贝插入,后来确认了下,确实是拷贝插入的,

最后搞清楚了原因,在循环定义的局部变量,在每次循环上,应该用的都是同样的地址,比如,

for(int i = 1; i <= 2; i++) {

     int a;

}

那么么,这两次循环中,a的地址都是一样的,这样,如果把 a 换成string型的,

虽然每次都是拷贝string插入了set,但是因为string的实际内容是作为指针标示在string里的,而又因为每次string的内存地址都是一样的,

因此,修改该string,就修改了指针指向的内容,而在set中的string,指针也是指向这块内容,因此就反应到已经进入set的string了,因为string在拷贝插入set中是浅拷贝,

这里,因为局部变量的地址一直不变,某种意义上像一个引用.

以后复习下 efficitive STL 和 STL源码剖析吧,局部变量这个,是C++规范没有定义的地方,因此取决与编译器的,不过貌似主流的都是重复利用了地址。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值