首页 > 解决方案 > const char* 向量的新值没有得到 push_back()

问题描述

我有一个 cons char* 向量。这实际上是一个时间戳。每次,我都在获取最后一个值,将其转换为整数,递增 40。然后将其作为 const char* 推回向量。我的问题是,新值没有得到 push_back()。向量已经包含一些值。

我试图创建实例而不是直接这样做而不是这样

string is = to_string(y);
some_vector.push_back(is.c_str());

我在做

string is = to_string(y);
const char * temp = is.c_str();
some_vector.push_back(temp);

我的完整代码是

vector<const char *> TimeConstraint; 
for (int i = 1; i <= 10; i++)
    {
        const char * tx = TimeConstraint.back();

        int y;
        stringstream strval;

        strval << tx;
        strval >> y;

        y = y + 40;

        string is = to_string(y);
        const char* temp_pointer = is.c_str();
        TimeConstraint.push_back(temp_pointer);


    } 

新值未添加到 TimeConstraint 向量

每次我必须 push_back() 向量的最后一个元素的增量值。请帮助我提前谢谢

标签: c++

解决方案


这:

    string is = to_string(y);
    const char* temp_pointer = is.c_str();
    TimeConstraint.push_back(temp_pointer);

是麻烦。由返回的指针只有在活着的时候is.c_str()才有效is,它只在循环的下一次迭代之前有效。

我建议您TimeConstraint改为保存std::string对象,然后执行以下操作:

    TimeConstraint.push_back(is);

然后您的容器会根据需要使字符串保持活动状态。

另一个问题是

const char * tx = TimeConstraint.back();

由于调用.back()empty是无效的std::vector。该代码会导致未定义的行为并使您的程序毫无意义。编译器不再有义务做任何明智的事情。


推荐阅读