You can’t iterate through a list with an integer, but you can declare j
as an iterator (std::list<int>::iterator j = adjList[i].begin();
) and use the asterisk like in pointers to get the element that an iterator is pointing at like this: cout << *j << ' ';
. If you want to print a vector of arrays, just do it like how you would normally print a 2D array. The std::list
container implements a linked list and is very different from containers that store elements in contiguous memory such as arrays and std::vector
, which is likely not what you want here since it doesn’t have random access.
By the way, if you want to pass large containers like vectors to a function like print()
that does not need to modify the vector, you should use a constant reference instead of copying the vector. There is something called a range based for loop in C++11 that can iterate through things like vectors without you having to worry about things like iterators, and a std::set
is probably more suited for implementing an adjacency list since it allows for checking if two vertices are adjacent with logarithmic complexity.
Lastly, in your input loop, you used adjList[u]
when that element does not exist yet since adjList
is empty. You should add a line adjList.resize(n)
after you input n to create the empty sets or just declare adjList
after you input n
and use n
as the constructor argument like this to tell the constructor to initialize adjList
with a bunch of empty sets: vector<set<int>> adjList(n);
.
Since it looks like you are doing a competitive programming problem, I would advise you to convert the input to zero indexing before doing any processing.
My code using range based for loops:
#include <iostream>
#include <vector>
#include <set>
void print(const std::vector<std::set<int>> &adjList)//pass by const reference
{
for(std::size_t i = 0; i < adjList.size(); i++)
{
std::cout << i << ": ";
for(auto &j : adjList[i])//range based for loop to iterate through adjList[i] and use the reference j to refer to each element
{
std::cout << j << ' ';
}
std::cout << '\n';
}
}
int main()
{
int n, m;
std::cin >> n >> m;
std::vector<std::set<int>> adjList(n); //adjList starts with n empty sets
for(int i = 0; i < m; i++)
{
int u, v;
std::cin >> u >> v;
adjList[u].insert(v);
adjList[v].insert(u);
}
print(adjList);
}
0
solved how do i print a vector of arrays/lists using int iterator in cpp?