Reputation:
I'm currently doing an activity w/ vectors and I stumbled upon this question.
A procedure that takes an array variable of size 4 by 4. The array variable should be string type. The contents of the array are illustrated below.
The contents:
aa ab ac ad
ba bb bc bd
ca cb empty cd
da db dc dd
This is what your procedure should do, gets the board and displays to the user as below,
1 2 3 4
5 6 7 8
9 10 empty 12
13 14 15 16
I managed to print it out as strings but I have no idea on how to turn it into int after printing.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<string> > thirdQuiz
{
{ "aa", "ab", "ac", "ad" },
{ "ba", "bb", "bc", "bd" },
{ "ca", "cb", "empty", "cd" },
{ "da", "db", "dc", "dd" },
};
// Displaying the 2D vector
for (int i = 0; i < thirdQuiz.size(); i++)
{
for (int j = 0; j < thirdQuiz[i].size(); j++)
{
cout << thirdQuiz[i][j] << " ";
}
cout << endl;
}
return 0;
}
Upvotes: 0
Views: 49
Reputation: 673
If I assume right, you need to display the index. Then several possibilities come around.
One is:
auto count = i * thirdQuiz[i].size() + j + 1;
But be aware this only works if the inner vectors all have the same size. for (int i = 0; i < thirdQuiz.size(); i++) {
for (int j = 0; j < thirdQuiz[i].size(); j++) {
if(!thirdQuiz[i][j].empty() && thirdQuiz[i][j] != "empty"){
std::cout << i * thirdQuiz[i].size() + j + 1 << " ";
continue;
}
std::cout << "empty" << " ";
}
std::cout << endl;
}
A more robust way would be to just count all entries in your vectors:
size_t count{};
for (auto const& inner_vec: thirdQuiz) {
for (auto const& string_val: inner_vec) {
++count;
if(!string_val.empty() && string_val != "empty"){
std::cout << count << " ";
continue;
}
std::cout << "empty" << " ";
}
std::cout << endl;
}
Upvotes: 0