将const char *转换为向量< double>更好的方法 [英] converting const char* to vector<double> better way
本文介绍了将const char *转换为向量< double>更好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过UDP接收 const char *
。此文本的大小不同(即不是固定大小)。此文本的值为double类型。我想将它转换为 vector< double>
。这是我做的。
I'm receiving const char*
via UDP. The size of this text varies (i.e. not fixed size). This text has values of double type. I want to convert it to vector<double>
. This what I've done.
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.
This is definitely not an elegant way but it did the trick. Any suggestions! I'm using 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);
这篇关于将const char *转换为向量< double>更好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文