Reputation: 25
I have a map:
std::map<string , double> params{{a , 1}, {b, 6 }, {c, 7}{d,8} }
I want to print it like a python dataframe:
a b c d
1 6 7 8
Also, I dont want it to run twice.
void join_parameters(std::pair<string , double> param){
std::map<string , double> params;
params.insert(param);
for(const auto& elem : params)
{
double a, b , c,d;
if (elem.first =="a"){
a = elem.second; }
else if (elem.first =="b"){
b = elem.second;}
else if (elem.first =="c"){
c = elem.second; }
else {
d = elem.second;
}
}
std::cout << "d " << "a "<< "b " << "c "<< "\n" << d << a << b << c <<std::endl ;
}
Do you have any suggestion for me?
Upvotes: 0
Views: 89
Reputation: 122830
Your code only works for a map with 4 elements and it assumes that those elements have keys "a"
till "d"
. If that is the case then I would suggest you to use a different data structure, for example
struct params_t {
double a,b,c,d;
};
If you do need the map then you should not make assumptions about number of elements or their keys.
You can use two strings to accumulate the two lines of output in a single loop:
#include <map>
#include <string>
#include <utility>
#include <iostream>
int main() {
std::map<std::string , int> params{{"a" , 1}, {"b", 6 }, {"c", 7},{"d",8} };
std::pair<std::string,std::string> lines;
for (const auto& e : params) {
lines.first += e.first + " ";
lines.second += std::to_string(e.second) + " ";
}
std::cout << lines.first << '\n';
std::cout << lines.second << '\n';
}
Note that I changed the mapped type to int
because it looks like you want to store integers. For double
you need to adjust the code to get propper formatting.
Upvotes: 1