我遇到了使用vector.push_back(value)
覆盖最终值而不是追加到最后的问题。为何会发生这种情况?我在矢量中有一个样本项,所以它的大小从未达到零。下面是代码..std :: vector覆盖最终值,而不是增长?
void UpdateTable(vector<MyStruct> *Individuals, MyStruct entry)
{
MyStruct someEntry;
bool isNewEntry = true;
for (int i = 0; i < Individuals->size(); i++)
{
if (!(strcmp(Individuals->at(i).sourceAddress, entry.sourceAddress)))
{
isNewEntry = false;
//snip. some work done here.
}
}
if(isNewEntry)
{
Individuals->push_back(entry);
}
}
这让我的第一个“示例”值留在,并将只允许向量中的一个项目。当添加2个新条目时,第二条将覆盖第一条,因此大小永远不会大于2.
编辑:更多代码,因为这显然不是问题?
void *TableManagement(void *arg)
{
//NDP table to store discovered devices.
//Filled with a row of sample data.
vector<MyStruct> discoveryTable;
MyStruct sample;
sample.sourceAddress = "Sample";
sample.lastSeen = -1;
sample.beaconReceived = 1;
discoveryTable.push_back(sample);
srand(time(NULL));
while(1)
{
int sleepTime = rand() % 3;
sleep(sleepTime);
MyStruct newDiscovery = ReceivedValue();
if (newDiscovery.lastSeen != -1000) //no new value from receivedValue()
{
UpdateTable(&discoveryTable, newDiscovery);
}
printTable(&discoveryTable);
}
return NULL;
}
为什么你使用strcmp()和行进,而不是某种形式的关联容器?不必要地覆盖isNewEntry。 – 2010-02-01 18:32:23
问题不在于您所显示的代码中,因此请显示更多代码,具体说明如何使用该功能。 – 2010-02-01 18:32:40
你如何检查?我非常怀疑'push_back'正在无情地覆盖着某些东西。人们会告诉你,我会同意:使用C++! 'std :: string','std :: find'和更合适的容器都可以存储。 – GManNickG 2010-02-01 18:33:02