【发布时间】:2014-10-11 20:56:00
【问题描述】:
我想知道是否有一种优雅的方式或内置函数将vector<double> 转换为vector<string>。我做的很简单
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> doubeVecToStr(const std::vector<double>& vec)
{
std::vector<std::string> tempStr;
for (unsigned int i(0); i < vec.size(); ++i){
std::ostringstream doubleStr;
doubleStr << vec[i];
tempStr.push_back(doubleStr.str());
}
return tempStr;
}
int main( int argc, char* argv[] )
{
std::vector<double> doubleVec;
doubleVec.push_back(1.0);
doubleVec.push_back(2.1);
doubleVec.push_back(3.2);
std::vector<std::string> doubleStr;
doubleStr = doubeVecToStr(doubleVec);
for (unsigned int i(0); i < doubleStr.size(); ++i)
std::cout << doubleStr[i] << " ";
std::cout << std::endl;
return 0;
}
【问题讨论】:
-
如果你不介意使用 Boost,你可以使用这个:boost.org/doc/libs/1_56_0/doc/html/string_algo/…
-
-1 这个问题不是关于(甚至没有提到)OP 后来claims 是他的目标以及问题的真正意义。
-
为什么需要一个字符串向量?为什么不在需要时转换浮点数?
-
@Cheersandhth.-Alf,很抱歉,但这绝对是巧合。我确实考虑过适合这个问题的另一个答案。再次抱歉。