gpt4 book ai didi

c++ - 将 const char* 转换为 vector 更好的方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:08:14 24 4
gpt4 key购买 nike

我收到了 const char*通过 UDP。此文本的大小各不相同(即不固定大小)。此文本具有 double 类型的值。我想将其转换为 vector<double> .这就是我所做的。

std::vector<double> convertToDoubVect(const char * buff)
{
std::vector<double> vec;
std::istringstream data(buff);

int i = 0, count = 0;

// get number of doubles in const char* by incrementing count
while( buff[i] != '\0' )
{
if ( buff[i] == ' ')
++count;
++i;
}

// allocate an array for the total doubles
double *n = new double[count+1];

// convert const char* to vector<double>
for ( int i(0); i <= count; ++i)
{
data >> n[i];
vec.push_back(n[i]);
}

delete n;

return vec;
}

int main()
{

const char *doubStr = "2.3 4.3 5.6 2.1 4.4 3.1";
std::vector<double> vec = convertToDoubVect(doubStr);

for ( int i(0); i < vec.size(); ++i)
{
std::cout << vec[i] << std::endl;
}

return 0;
}

这绝对不是一种优雅的方式,但它确实起到了作用。有什么建议么!我正在使用 visual studio 2010。

最佳答案

#include <sstream>
#include <vector>
#include <iterator>

const char* doubStr = "2.3 4.3 5.6 2.1 4.4 3.1";
std::istringstream iss(doubStr);
std::istream_iterator<double> it(iss), end;
std::vector<double> v(it, end);

Demo.

关于c++ - 将 const char* 转换为 vector<double> 更好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25453368/

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