C++学习杂记190401

今天的第一点,是关于使用for循环遍历string对象的内容是string长度发生变化的情况,例如下面这段:

#include<iostream>
#include<string>

using namespace std;

int main() {
    string a="1234567";
    for(int j;j<a.length();j++){
        a.erase(0,1);
        cout<<a<<endl;
        cout<<"j: "<<j<<endl;
    }
}

这段程序的输出结果为:

234567
j: 0
34567
j: 1
4567
j: 2
567
j: 3

我们可以看到,使用erase方法,随着string的长度变化,for循环中的条件判断中a.length()并不会始终使用最初的a.length(),而是也是在跟着不断变化,这样就不必担心出现string的length减小后访问越界的情况。

然而与之对比的,python也有类似的现象,比如下面这段:

a = list(range(1, 8))
for i in a:
    a.pop(0)
    print(i, a)

输出结果为:

1 [2, 3, 4, 5, 6, 7]
3 [3, 4, 5, 6, 7]
5 [4, 5, 6, 7]
7 [5, 6, 7]

这里用于迭代的lista也是随着迭代而不断变化的,但是这里与C++有一个差别就是,因为foreach循环的实现机制类似于一个迭代器,每次虽然总长度会减少,但是迭代的位置仍然是不断向前的,所以会出现这样的情况。


今天的练习是 UVa 489

其中我使用的count方法,在<algorithm>中,此外,在猜中时,由于再此猜同样的也算错,所以要对猜过的做特殊处理,其实这里完全没必要用erase,直接换成空格这样的字符即可。

#include<iostream>
#include<string>
#include<algorithm>

using namespace std;

int main() {
    while (true) {
        int kase;
        string a, b;
        cin >> kase;
        if (kase == -1) break;
        cin >> a >> b;
        int wrong = 0;
        for (int i = 0; i < b.length(); i++) {
            if (!count(a.begin(), a.end(), b[i])) {
                wrong++;
                continue;
            }
            for (int j=0; j < a.length(); j++) {
                if (a[j] == b[i]) a.erase(j, 1);
            }
        }
        if (wrong >= 7) cout << "You lose." << endl;
        else if (a != "") cout << "You chickened out." << endl;
        else cout << "You win" << endl;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值