Re: convert std:: vector of strings/doubles to arrays
puzzlecracker wrote:
> In my case, I want to convert std::vector of names and std::vector of
> values to char ** and double *
> Please keep in mind that order of names and values matters and should
> match.
>
> Thanks
Is it as simple? Or I did not understand something!
**names is almost the same as *names[] and *values is almost the same as
values[]. The little difference is the table / array a pointer
containing the address is a const pointer u cant "move" it
double * const values[] = {1.5, 3, 4.5};
so basically the program would be as below:
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> v_str;
vector<double> v_dbl;
v_str.push_back("aaa");
v_str.push_back("bbb");
v_str.push_back("ccc");
v_str.push_back("ddd");
v_dbl.push_back(1.5);
v_dbl.push_back(3.0);
v_dbl.push_back(4.5);
// definition of arrays and filling them with vectors val
char* names[v_str.size()];
double values[v_dbl.size()];
for(size_t i=0; i<v_str.size(); ++i) {
// const_cast<double*> removes const given by c_str()
// either u define names[] with const or keep
// const_cast<double*>() here in order for the code to work.
names[i] = const_cast<char*>(v_str[i].c_str());
}
for(size_t i=0; i<v_dbl.size(); ++i) {
values[i] = v_dbl[i];
}
// end here is only checking that everything works fine
for(size_t i=0; i<v_str.size(); ++i) {
cout << names[i] << endl;
}
for(size_t i=0; i<v_dbl.size(); ++i) {
cout << values[i] << endl;
}
return 0;
}