Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

initialize 2d vector in c++

So, I have the following code in c++:

This is the 2d vector:

vector<vector<int>> adj;

Initialization of 2d vector:

adj[0].push_back(1);
adj[0].push_back(2);
adj[1].push_back(3);
adj[1].push_back(4);
adj[1].push_back(5);

Printing the vector:

for(auto i : adj) {
    for(auto j : i)
        cout << j << " ";
    cout << endl;
}

Compilation is without error but when I try to run it shows nothing. How to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...