Reputation: 159
In the code below i have 2 arrays, 1 containing 3 names, the other, a 2 dimensional array containing 21 numbers
I want to know how to print two arrays next to each other rather than one on top and one underneath. With the code shown below my output looks like:
name1
name2
name3
37 37 63 38 27 56 55
37 54 78 31 26 67 44
86 11 23 6 90 87 33
and i want it to display as such
name1 37 37 63 38 27 56 55
name2 37 54 78 31 26 67 44
name3 86 11 23 6 90 87 33
here is the function i am using to display the arrays
void printArrays(const int array1[][NUM_DAYS], const string array2[])
{
cout << "Name \t\t\t Day 1\t Day 2\t Day 3\t Day 4 \t Day 5\t Day 6\t Day 7" << endl;
for (int i = 0; i < NUM_MONKEYS; i++)
{
cout << array2[i] << endl;
}
cout << endl;
for (int row = 0; row < NUM_MONKEYS; row++)
{
for (int col = 0; col < NUM_DAYS; col++)
{
cout << array1[row][col] << " ";
}
cout << endl;
}
Upvotes: 0
Views: 2634
Reputation: 199
Your solution can be simplified using the C++11 Range-based for loop.
#include <iostream>
#include <vector>
int main()
{
std::vector<char*> m_Str{"name1", "name2", "name3"};
std::vector<std::vector<int>> m_Array{ { 37, 37, 63, 38, 27, 56, 55 },
{ 37, 54, 78, 31, 26, 67, 44 },
{ 86, 11, 23, 6, 90, 87, 33 } };
for(const auto& str : m_Str)
{
static auto i = 0;
std::cout << str << '\t';
for(const auto& ele : m_Array[i])
{
std::cout << ele << ' ';
}
std::cout << std::endl;
i++;
}
}
Upvotes: 0
Reputation: 1229
You are starting a new loop to iterate through array2.You just need to iterate through the same index of row as you did for the first array.check the code:
void printArrays(const int array1[][NUM_DAYS], const string array2[])
{
cout << "Name \t\t\t Day 1\t Day 2\t Day 3\t Day 4 \t Day 5\t Day 6\t Day 7" << endl;
for (int i = 0; i < NUM_MONKEYS; i++)
{
cout << array2[i] << " ";
for (int col = 0; col < NUM_DAYS; col++)
{
cout << array1[i][col] << " ";
}
cout << endl;
}
}
Upvotes: 1
Reputation: 11018
Why don't you just declare three std::vector
's and print them with it's name?
void print(const vector<int>& vec, const string& name)
{
cout << name << "\t";
for (const auto& i : vec)
cout << i << " ";
cout << '\n';
}
int main()
{
vector<int> name1 { 37, 37, 63, 38, 27, 56, 55 };
vector<int> name2 { 37, 54, 78, 31, 26, 67, 44 };
vector<int> name3 { 86, 11, 23, 6, 90, 87, 33 };
print(name1, "name1");
print(name2, "name2");
print(name3, "name3");
}
Output:
name1 37 37 63 38 27 56 55
name2 37 54 78 31 26 67 44
name3 86 11 23 6 90 87 33
Upvotes: 0