Reputation: 3531
I have one data structure.
map <const char*, vector<double> > m;
Key values
AA 1 2 3 1 2 1 2 3
BB 2 3 4 1 2 3 4 5
CC 2 3 4 1 2 3 4 5
I want to print output in below format:
AA BB CC
1 2 2
2 3 3
3 4 4
1 1 1
2 2 2
1 3 3
2 4 4
3 5 5
How can i implement this in efficient way? Iterating over map and copying vector is very time consuming.
Regards
Upvotes: 2
Views: 1405
Reputation: 45470
The idea is to iterator first round to print key of map, then go though each vector and print out element one by one if any.
void func()
{
std::map<std::string, std::vector<int> > m;
m["AA"] = {1, 2, 3, 1, 2, 1, 2, 3};
m["BB"] = {2, 3, 4, 1, 2, 3, 4, 5, 5 };
m["CC"] = {2, 3, 4, 1, 2, 3, 4, 5};
size_t size = 0;
for (auto item = m.begin(); item != m.end(); ++item)
{
std::cout << item->first << '\t';
if (size < item->second.size())
{
size = item->second.size();
}
}
std::cout << std::endl;
for (size_t i = 0; i< size; i++)
{
for (auto item = m.begin(); item != m.end(); ++item)
{
if (i < item->second.size())
{
std::cout << item->second.at(i) << '\t';
}
}
std::cout << std::endl;
}
}
If all vectors have same size, you could ignore the size check and use [] operator to get better speed.
for (size_t i = 0; i< size; i++)
{
for (auto item = m.begin(); item != m.end(); ++item)
{
std::cout << item->second[i] << '\t';
}
std::cout << std::endl;
}
see sample code link, enjoy
Upvotes: 3
Reputation: 3554
What I come up with.
Warning: not tested!
using namespace std;
map <const char*, vector<double> > m;
vector<double>::size_type int index = -1;
map <const char*, vector<double> >::size_type finishedVectors = 0;
while(1)
{
for(map <const char*, vector<double> >::iterator it = m.begin(); it != m.end(); ++it)
{
if(index == -1)
{
std::cout << it->first << "\t";
}
else
{
if(index < it->second.size())
{
std::cout << it->second[i] << "\t";
}
else
{
++finishedVectors;
}
}
}
if(finishedVectors == m.size())
{
break;
}
++index;
}
Upvotes: 1