C++使用for(:)遇到的BUG

简化问题代码如下

#include<bits/stdc++.h>

using namespace std;




int main()
{
    vector<int> vec;
    vector<int> f(9,0);
    for(int i = 0; i<9; i ++)vec.push_back(i);
//    for(int j = 0; j < vec.size(); j ++){
//        int t = vec[j];
//        cout<<t<<endl;
//        f[t] = f[t];
//        vec.push_back(1);
//    }
	for(int t:vec){
        cout<<t<<endl;
        f[t] = f[t];
        vec.push_back(1);
    }
    return 0;
}

使用for(:)会报segment fault的错误,原因是访问到了未定义的地址,即t访问到了负数,f[t]越界访问。但是使用注释中的索引访问会正常运行,即死循环访问f[1]

经过vscode和devc++编译器测试,猜测是vector的foreach循环使用首尾迭代器(指针)实现,vector使用push_back扩容时回收了地址,导致原有的指针指向错误数据,而索引寻址不会出现指针问题

后续有时间阅读书籍查询c++的for(:)实现


以下可忽略

原问题代码如下:

#include<bits/stdc++.h>

using namespace std;

const int M = 1 << 20;


int n, m, k;
vector<int> states;
int f[M];
bool st[M];


int main()
{
    cin >> n >> m >> k;

    
    for (int i = 0; i < n; i ++ )
    {
        int state = 0;
        for (int j = 0; j < k; j ++ )
        {
            int c;
            cin >> c;
            state |= 1 << c - 1;
        }

        states.push_back(state);
    }
    vector<int> sst;
    sst.push_back(0);
    st[0] = 1;
    memset(f,0x3f, sizeof f);
    f[0] = 0;
    
    for(int i = 0; i < n; i ++){
        for(int t:sst){
            // int t = sst[j];//segment fault
            int s = t|states[i];
            f[s] = min(f[t]+1, f[s]);
            if(!st[s]){
                sst.push_back(s);
                st[s] = 1;
            }
        }
    }
    
    
    int ans=f[(1<<m)-1];
    if(ans == 0x3f3f3f3f)cout<<-1<<endl;
    else cout<<ans<<endl;
    
    
    return 0;
}

错误样例如下:

50 20 6
4 4 4 10 10 4
2 20 2 20 2 9
10 16 4 4 10 16
18 1 18 1 1 16
17 10 10 10 17 17
7 13 13 7 13 7
17 17 17 17 1 17
3 17 17 17 17 17
12 8 12 8 8 12
19 9 9 19 19 19
9 9 9 9 11 9
18 18 18 18 18 8
1 11 11 5 5 11
9 17 17 17 8 9
9 9 9 9 9 14
3 2 9 2 2 3
5 5 8 5 8 5
13 16 17 17 13 13
10 10 10 16 10 18
10 8 10 10 8 10
8 12 12 12 12 8
18 18 13 18 18 13
18 3 18 3 3 18
13 10 10 10 13 6
8 11 5 8 11 8
16 13 6 16 6 13
12 3 11 12 3 11
12 12 4 12 4 16
1 12 1 12 1 1
13 13 1 1 1 14
12 6 12 12 6 12
1 15 1 1 1 1
4 4 16 4 3 3
4 3 3 3 3 4
18 18 18 18 18 19
11 8 11 20 20 11
3 3 5 3 3 3
19 2 2 19 2 19
6 19 19 19 19 6
20 20 10 10 9 10
10 10 10 7 7 7
2 2 18 2 18 18
4 16 4 4 16 16
13 4 4 4 9 4
4 16 16 16 16 16
6 14 14 14 14 14
10 4 10 4 4 4
3 11 3 9 9 11
10 20 8 20 8 20
14 16 14 14 14 16

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最后一只三脚兽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值