You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++自定义类初始化列表异常:vector<vector<Interval>>出现无效0值

问题排查:vector<vector>初始化导致无效区间值

问题现象

使用C++20初始化vector<vector<Interval>>类型的schedule时,输出结果出现0->0的无效值,而非预期的四个正确区间。

错误代码

#include <bits/stdc++.h>
using namespace std;

class Interval {
public:
    int start;
    int end;

    Interval() {}

    Interval(int _start, int _end) {
        start = _start;
        end = _end;
    }
};

vector<Interval> solve(vector<vector<Interval>> schedule) {
    vector<Interval> allSchedule;

    for(auto it : schedule) {
        for(auto it1 : it) {
            allSchedule.push_back(it1);
        }
    }

    auto comparator = [](Interval a, Interval b) {
        return a.start > b.start;
    };
    sort(allSchedule.begin(), allSchedule.end(), comparator);

    return allSchedule;
}

int main() {
    vector<vector<Interval>> schedule;
    schedule.push_back({new Interval(1,2), new Interval(5,6)});
    schedule.push_back({new Interval(1,3), new Interval(4,10)});
    vector<Interval> allSchedules = solve(schedule);
    for(auto it : allSchedules) {
        cout << it.start << " -> " << it.end << endl;
    }
    return 0;
}

非预期输出

1 -> 2
1 -> 3
0 -> 0
0 -> 0

问题原因

核心错误出在main函数的初始化逻辑:

  • new Interval(1,2)返回的是Interval*类型的指针,但vector<vector<Interval>>的元素是Interval对象,并非指针类型。
  • 编译器无法将指针直接转换为Interval对象,会调用Interval的默认构造函数创建空对象,这些对象的start和end属于未初始化状态(最终表现为0值,是未初始化栈内存的默认值)。
  • 前两个看似正确的输出是指针地址被错误转换为整数后的巧合值,并非正确构造的区间。

修正方案

去掉new关键字,直接构造Interval对象:

int main() {
    vector<vector<Interval>> schedule;
    // 直接构造Interval对象,而非使用new创建指针
    schedule.push_back({Interval(1,2), Interval(5,6)});
    schedule.push_back({Interval(1,3), Interval(4,10)});
    vector<Interval> allSchedules = solve(schedule);
    for(auto it : allSchedules) {
        cout << it.start << " -> " << it.end << endl;
    }
    return 0;
}

额外优化建议

  • 给Interval添加列表初始化支持,简化代码:
    class Interval {
    public:
        int start;
        int end;
    
        Interval() = default;
        Interval(int _start, int _end) : start(_start), end(_end) {}
        // 支持列表初始化
        Interval(std::initializer_list<int> init) {
            if (init.size() == 2) {
                auto iter = init.begin();
                start = *iter;
                end = *(++iter);
            }
        }
    };
    
    之后初始化可简化为:
    schedule.push_back({{1,2}, {5,6}});
    schedule.push_back({{1,3}, {4,10}});
    
  • 将solve函数的参数改为const vector<vector<Interval>>&,避免不必要的拷贝操作。

内容的提问来源于stack exchange,提问作者Nidhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 22:14:50