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

vector<const char*>无法push_back新增时间戳值的技术求助

搞定你的容器添加问题!

为啥新值看起来没成功添加?

嘿,这个问题我之前踩过坑!核心问题是你存到容器里的指针都是悬空的:

  • 循环里的string is是局部变量,每次循环结束后这个字符串对象就被销毁了,它通过c_str()返回的指针也就指向了已经被释放的内存。
  • 你把这个无效指针push到vector<const char*>里,后续访问时内存已经不属于你的程序了,看起来像是"没添加成功",实际是指针指向的内容早就失效了。

最省心的解决方案:换用vector<string>

别跟指针较劲了,直接把容器改成vector<string>就万事大吉!字符串的内存会被容器自动管理,完全不用操心生命周期的问题。修改后的代码如下:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int main() {
    vector<string> TimeConstraint;
    // 先给容器加个初始值,比如:
    TimeConstraint.push_back("100");
    
    for (int i = 1; i <= 10; i++) {
        // 直接取最后一个字符串引用
        const string& last_val = TimeConstraint.back();
        int y;
        stringstream strval;
        strval << last_val;
        strval >> y;
        y += 40;
        // 直接把新生成的字符串push进去
        TimeConstraint.push_back(to_string(y));
    }
    
    // 验证一下结果
    for (const auto& val : TimeConstraint) {
        cout << val << endl;
    }
    return 0;
}

要是非得用vector<const char*>怎么办?

如果因为某些限制必须用const char*类型的容器,那你得手动管理内存,确保每个指针指向的内存不会被释放。比如用new来动态分配字符串内存:

#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <cstring>

using namespace std;

int main() {
    vector<const char*> TimeConstraint;
    // 初始值也要用动态分配的内存,比如:
    char* initial = new char[4];
    strcpy(initial, "100");
    TimeConstraint.push_back(initial);
    
    for (int i = 1; i <= 10; i++) {
        const char* tx = TimeConstraint.back();
        int y;
        stringstream strval;
        strval << tx;
        strval >> y;
        y += 40;
        string is = to_string(y);
        // 分配足够的内存(要算上末尾的'\0')
        char* temp_ptr = new char[is.size() + 1];
        strcpy(temp_ptr, is.c_str());
        TimeConstraint.push_back(temp_ptr);
    }
    
    // 别忘了最后手动释放所有内存,不然会泄漏!
    for (const char* ptr : TimeConstraint) {
        delete[] ptr;
    }
    return 0;
}

⚠️ 友情提示:这种方法很容易忘释放内存导致泄漏,除非迫不得已,强烈建议用第一种vector<string>的方案!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:25:06