c++ - 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() 向量的最后一个元素的增量值。请帮助我提前谢谢
解决方案
这:
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
。该代码会导致未定义的行为并使您的程序毫无意义。编译器不再有义务做任何明智的事情。
推荐阅读
- google-cloud-platform - 在不同的端口上发布 Ingress 健康检查
- sorting - 按当前或先前状态排序
- wordpress - 将我的域从 godaddy 指向 ec2 Ubuntu wordpress
- python - Python 在大整数矩阵乘积上的精度和性能
- ffmpeg - FFMPEG - 将 UInt16 数据转换为 .264
- node.js - 单元和 e2e 测试 grpc 微服务
- jose4j - jose4j JSONAware 的反面
- javascript - 关联数组:无法设置未定义的属性
- java - maven依赖地狱:java.lang.NoSuchMethodError
- django - Django:如何使用两个同时连接到一个数据库?