I want to make sure I copied the 2D array correctly into the 2D vector? But I don't know how can I print this?
Thank you in advance:
int path1[2][6] = {{6, 0, 1, 5, 6}, {6, 2, 4, 3, 6}};
vector<vector<int>> path2;
vector<int> temp; // For simplicity
for (int x = 0; x <= k; x++)
{
for (int y = 0; y < customer_inroute[x]; y++)
{
temp.push_back(path1[x][y]);
}
path2.push_back(temp);
}
vector<vector<int>>::iterator it;
it = path2.begin();
for (it = path2.begin(); it < path2.end(); it++)
std::cout << ' ' << * it;
cout << '\n';
First, i have no idea what customer_inroute[x]
is, but next time include more real code with your question. That said, save yourself some typing and do this:
#include <iostream>
#include <vector>
int main()
{
int path1[2][6]={{6,0,1,5,6},{6,2,4,3,6}};
std::vector< std::vector<int> > path2;
for (auto& row : path1)
path2.emplace_back(std::begin(row), std::end(row));
// send copy to stdout
for (auto& row : path2)
{
for (auto val : row)
std::cout << val << ' ';
std::cout << '\n';
}
return 0;
}
And I should note your original path1
rows are declared to be 6 elements wide, yet you only provide 5 in each initializer list. As a result, the last element is zero filled. The resulting output of the above looks like this, btw:
Output
6 0 1 5 6 0
6 2 4 3 6 0
There are several ways. This is one:
for (int i=0; i<path2.size(); ++i) {
for (int j=0; j<path2[i].size(); ++j) {
cout << path2[i][j] << " ";
}
cout << endl;
}
Another, with range-based for (C++ 11):
for (const auto& inner : path2) {
for (auto value : inner) {
cout << value << " ";
}
cout << endl;
}
This should do the trick if you want to use iterators:
vector<vector<int>::iterator it;
vector<int>::iterator it_inner;
for ( it = path2.begin(); it != path2.end; it++ )
{
for ( it_inner = (*it).begin(); it_inner != (*it).end(); it_inner++ )
{
cout << ' ' << *it_inner;
}
cout << endl;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.