DataMiner
DataMiner

Reputation: 325

To convert datatype of a vector

Please guide me how i can convert a vector of string

std::vector<string> strVect; --> std::vector<float or double> flVect;

(e.g. strVect contains values like { "0.1111", "0.234", "0.4556"})

into a vector of floats using c++.

Thanks in advance.

Upvotes: 2

Views: 2030

Answers (2)

Christian Rau
Christian Rau

Reputation: 45948

In addition to the existing answers, a very easy way is to use C++11 string conversion functions and C++11 lambdas:

std::vector<string> strVect = ...;
std::vector<float> flVect(strVect.size());
std::transform(strVect.begin(), strVect.end(), flVect.begin(), 
               [](const std::string &arg) { return std::stof(arg); });

And analogous for double, just with std::stod, of course.

Upvotes: 3

Alex
Alex

Reputation: 7838

Here's a solution without using boost:

std::vector<string> strVect;
//...
std::ostringstream ss;
std::vector<double> flVect( strVect.size() );
for( size_t i = 0; i < strVect.size(); ++i )
{
    ss.str(strVect[i]);
    ss >> flVect[i];
}

Upvotes: 2

Related Questions