gpt4 book ai didi

c++ - std::vector 的赋值效果错误?

转载 作者:行者123 更新时间:2023-11-30 04:04:27 25 4
gpt4 key购买 nike

错误代码如下:

#include <vector>
#include <string>
#include <iostream>
void foo(const std::vector<double> & in) {
std::vector<const char *> v(5);
size_t indx = 0;
for(auto & tmp : in) {
auto temp = std::to_string(tmp);
v[indx] = temp.c_str();
std::cout << "right: "<< v[indx] << std::endl;
indx += 1;
}
std::cout << "wrong: " << v[0] << std::endl;
std::cout << "wrong: " << v[1] << std::endl;
std::cout << "wrong: " << v[2] << std::endl;
std::cout << "wrong: " << v[3] << std::endl;
std::cout << "wrong: " << v[4] << std::endl;
}

int main(int argc, char *argv[])
{
std::vector<double> tmp = {0.01, 0.02, 0.03, 0.04, 0.05};
foo(tmp);
return 0;
}

我编译代码,在for-loop中,打印正确,但外面打印错误,这里有什么问题?

最佳答案

错误是std::to_string(tmp)创建一个临时对象,该对象在分号后立即销毁。因此 c_str() 指针变为无效。

为什么不使用 std::vector<std::string>存储你的字符串?

std::vector<std::string> v(5);
size_t indx = 0;
for(auto & tmp : in) {
v[indx] = std::to_string(tmp);
std::cout << "right: "<< v[indx] << std::endl;
indx += 1;
}

关于c++ - std::vector<const char *> 的赋值效果错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23732151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com