有没有办法在 C++ 中将犰狳向量转换为字符串?

Is there a way to convert Armadillo vector to a string in C++?

我想知道是否有办法将犰狳向量转换为标准字符串。例如,如果我有这个向量:

arma::vec myvec("1 2 3"); //create a vector of length 3 

如何制作:

std::string mystring("1 2 3");

来自它?

这应该有效:

std::ostringstream s;
s << myvec;
std::string mystring = s.str();

使用 ostringstream, .raw_print(), .st(), .substr() 的组合,如下所示。

// vec is a column vector, or use rowvec to declare a row vector
arma::vec myvec("1.2 2.3 3.4");  

std::ostringstream ss;

// .st() to transpose column vector into row vector
myvec.st().raw_print(ss);  

// get string version of vector with an end-of-line character at end
std::string s1 = ss.str();

// remove the end-of-line character at end
std::string s2 = s1.substr(0, (s1.size() > 0) ? (s1.size()-1) : 0);

如果您想更改格式,请查看 fmtflags:

std::ostringstream ss;
ss.precision(11);
ss.setf(std::ios::fixed);