When you write adj[0]
, you're implicitly assuming that the vector has a size of at least 1, in order for the zeroth element to exist. This is not the case for an empty vector, such as a newly initialized one. Unfortunately, this does not guarantee an error of any kind, it is Undefined Behavior, and the compiler is allowed to let literally anything happen. To avoid it, you need to make room for those elements, which can be done in a number of ways:
adj.resize(2); // now size == 2, and [0] and [1] can be safely accessed
adj[0].push_back(1);
adj[1].push_back(3);
or alternatively
adj.push_back({}); // append default-constructed vector
adj.back().push_back(1); // append 1 to the above vector
or, perhaps most concisely:
adj = {
{1, 2},
{3, 4, 5}
};
// adj now contains two vectors containing {1, 2} and {3, 4, 5} respectively
If you want to use the subscript []
operator for indexed access to a vector, consider using vector.at()
, which performs the same functionality but throws an exception if the index is out of range. This can be very helpful for debugging.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…