2D std::vector 替换值 - 需要删除以避免内存泄漏?
2D std::vector replace values - need for delete to avoid memory leaks?
我有一个二维向量,我希望所有 int
值都替换为 zeros.
虽然这段代码似乎有效,但我想知道:
我是否需要在重新分配之前删除旧矢量(第 5 行),因为 std::vector<int>
的副本存储在 line
中?
这是替换值的最佳方式(使用迭代器)吗?
代码:
for (std::vector< std::vector<int> >::iterator it = data.begin(); it != data.end(); ++it)
{
std::vector<int> line = *it;
std::fill(line.begin(), line.end(), 0);
*it = line; // line 5
}
我想避免内存泄漏。
您不需要 delete
您的代码中的任何内容,因为您没有使用 new
创建任何内容。
如果你也想在一行中完成所有这些,你可以使用 std::for_each
和 std::fill
:
#include <algorithm>
#include <vector>
std::vector<std::vector<int>> a;
// set every element in two dimensional vector to 5
std::for_each(a.begin(), a.end(), [](std::vector<int> &x){std::fill(x.begin(), x.end(), 5);});
与您的评论相关的附录:
是的,您的原始向量存储在堆栈中。由于您没有传递自定义分配器,因此向量将使用 std::allocator
来分配其元素(在您的情况下是 int 向量)。 std::allocator
在动态内存中分配这些元素,也就是堆,但您无需担心释放或删除此内存,因为它由向量的内部处理。这意味着如果调用向量的析构函数(例如,因为它超出范围),内存最晚会被删除,或者如果您更改向量的大小,内存可能会更早被删除。
我有一个二维向量,我希望所有 int
值都替换为 zeros.
虽然这段代码似乎有效,但我想知道:
我是否需要在重新分配之前删除旧矢量(第 5 行),因为
std::vector<int>
的副本存储在line
中?这是替换值的最佳方式(使用迭代器)吗?
代码:
for (std::vector< std::vector<int> >::iterator it = data.begin(); it != data.end(); ++it)
{
std::vector<int> line = *it;
std::fill(line.begin(), line.end(), 0);
*it = line; // line 5
}
我想避免内存泄漏。
您不需要 delete
您的代码中的任何内容,因为您没有使用 new
创建任何内容。
如果你也想在一行中完成所有这些,你可以使用 std::for_each
和 std::fill
:
#include <algorithm>
#include <vector>
std::vector<std::vector<int>> a;
// set every element in two dimensional vector to 5
std::for_each(a.begin(), a.end(), [](std::vector<int> &x){std::fill(x.begin(), x.end(), 5);});
与您的评论相关的附录:
是的,您的原始向量存储在堆栈中。由于您没有传递自定义分配器,因此向量将使用 std::allocator
来分配其元素(在您的情况下是 int 向量)。 std::allocator
在动态内存中分配这些元素,也就是堆,但您无需担心释放或删除此内存,因为它由向量的内部处理。这意味着如果调用向量的析构函数(例如,因为它超出范围),内存最晚会被删除,或者如果您更改向量的大小,内存可能会更早被删除。