在 C++ 中初始化二维向量 [英] initialize 2d vector in c++

查看:55
本文介绍了在 C++ 中初始化二维向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我在 C++ 中有以下代码:

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

这是二维向量:

vector<vector<int>> adj;

二维向量的初始化:

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);

打印向量:

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?

推荐答案

当您编写 adj[0] 时,您隐含地假设向量的大小至少为 1,以便存在第零个元素.这不是空向量的情况,例如新初始化的向量.不幸的是,这并不能保证任何类型的错误,它是未定义的行为,并且允许编译器让任何事情发生.为避免这种情况,您需要为这些元素腾出空间,这可以通过多种方式完成:

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);

或者替代

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

如果您想使用下标 [] 运算符对向量进行索引访问,请考虑使用 vector.at(),它执行相同的功能,但如果索引超出范围则抛出异常.这对调试非常有帮助.

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.

这篇关于在 C++ 中初始化二维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆