std::向量列表中的内存位置超出范围 我的最终目标是使用C++中已知的向量列表将值分配给未初始化的向量。下面是我的尝试 std::vector<TTableEntry>& t_entry_vector = tTable->getTTableEntries();
但该尝试失败,并返回一个运行时错误,表示内存位置超出范围。我是C++和向量类的新手。有人能帮我弄清楚吗?你必须控制向量的大小std::向量列表中的内存位置超出范围 我的最终目标是使用C++中已知的向量列表将值分配给未初始化的向量。下面是我的尝试 std::vector<TTableEntry>& t_entry_vector = tTable->getTTableEntries();,c++,vector,C++,Vector,但该尝试失败,并返回一个运行时错误,表示内存位置超出范围。我是C++和向量类的新手。有人能帮我弄清楚吗?你必须控制向量的大小 int index = 0; for (const auto it: t_entry_vector) { if(b_entry_vector.size() < index +1) continue; b_entry_vector[index].setA(it->getA()); b_e
int index = 0;
for (const auto it: t_entry_vector)
{
if(b_entry_vector.size() < index +1)
continue;
b_entry_vector[index].setA(it->getA());
b_entry_vector[index].setB(it->getB());
bTable->addBTableEntry(b_entry_vector[index]);
index++;
}
或
差不多吧。
此外,如果您有未初始化的b_entry_vector,并且希望将值放入其中,则可以执行以下操作:
for (int index = 0; index < t_entry_vector.size(); index++)
{
BTableEntry newEntry;
newEntry.setA(t_entry_vector[index]->getA());
newEntry.setB(t_entry_vector[index]->getB());
b_entry_vector.push_back(newEntry);
bTable->addBTableEntry(b_entry_vector[index]);
}
您必须了解,b_entry_vector.reservet_entry_vector.size不会用值填充向量,而是只为它们分配一个位置。
如果您尝试使用空选择作为值,您将得到一个内存访问错误。
如果你已经调整了向量的大小,你应该这样做:
for (int index = 0; index < t_entry_vector.size(); index++)
{
BTableEntry newEntry;
newEntry.setA(t_entry_vector[index]->getA());
newEntry.setB(t_entry_vector[index]->getB());
b_entry_vector[index] = newEntry;
bTable->addBTableEntry(b_entry_vector[index]);
}
但您仍然必须控制向量大小,因此,如果没有太多值,请使用push_back。阅读有关vector的内容,这是什么,以及当您使用push_back函数时vector如何为新值分配内存。如注释所述,您会遇到异常,因为您的b_entry_vector的大小为零 因此,如果您想继续使用填充新向量。至少,您只需执行以下操作:
// Initialize the new vector with a fixed size and then you can fill it
// as you see fit. You will not see the exception now.
std::vector<BTableEntry> b_entry_vector( t_entry_vector.size() );
此外,您也可以这样做:
// This would just copy the t_entry_vector into b_entry_vector.
std::vector<BTableEntry> b_entry_vector( t_entry_vector );
如果b_entry_vector有0个元素,则不能在其上使用.at。您必须首先添加元素,例如,使用.push_back或.resize.b_entry_向量最初的大小为零。因此,b_entry_vector.atindex将始终引发异常。这就是它被指定的方式。我已经按照上面的方式进行了编辑。但问题仍然存在。我将尝试以下注释调用保留的可能副本不会更改向量的大小。它改变了容量,这是不一样的。
for (int index = 0; index < t_entry_vector.size(); index++)
{
BTableEntry newEntry;
newEntry.setA(t_entry_vector[index]->getA());
newEntry.setB(t_entry_vector[index]->getB());
b_entry_vector[index] = newEntry;
bTable->addBTableEntry(b_entry_vector[index]);
}
// Initialize the new vector with a fixed size and then you can fill it
// as you see fit. You will not see the exception now.
std::vector<BTableEntry> b_entry_vector( t_entry_vector.size() );
// This would just copy the t_entry_vector into b_entry_vector.
std::vector<BTableEntry> b_entry_vector( t_entry_vector );