与将新内容分配给向量的指针斗争

Struggling with pointers to Assign new contents to a vector

本文关键字:指针 斗争 向量 新内容 分配      更新时间:2023-10-16

我要做的是将类的实例添加到向量的特定索引中。这个索引可以是最初不存在的,也可以是一个已被清除的现有索引,并且正在向该位置写入一个新的类实例。

下面是我一直用来尝试将这些实例写入向量的函数,并在底部注释,您可以看到我尝试使用的其他两个方法,显然使用push_back只能在末尾添加新向量。

我有一种感觉,分配可能只能添加数据到现有的元素?插入可能会添加新元素并向下移动现有元素,而不是覆盖。只是想弄清楚一点,因为c++教程已经开始让我困惑了。

另外,引用/差异/调用Person向量(在本例中被称为"allthePeople")的正确方法是什么,以便可以更改其数据?

void createnewPerson(int assignID, RECT startingpoint, vector<Person>* allthePeople, int framenumber) {
    Person newguy(assignID, startingpoint, framenumber);
    std::cout << "New Person ID number: " << newguy.getIDnumber() << std::endl;
    std::cout << "New Person Recent Frame:  " << newguy.getlastframeseen() << std::endl;
    std::cout << "New Person Recent history bottom:  " << newguy.getrecenthistory().bottom << std::endl;
    int place = assignID - 1;
    //This is where I am confused about referencing/dereferencing
    allthePeople->assign(allthePeople->begin() + place, newguy);
    //allthePeople->insert(place, newguy);
    //allthePeople->push_back(newguy);
}

也只是为了澄清,"place"总是比"assignID"小1,因为向量位置从0开始,我只是想让它们的ID号从1开始,而不是0。

------------- 编辑:补充说如果回路,解决问题 -----------------

void createnewPerson(int assignID, RECT startingpoint, vector<Person>* allthePeople, int framenumber) {
    Person newguy(assignID, startingpoint, framenumber);
    std::cout << "New Person ID number: " << newguy.getIDnumber() << std::endl;
    std::cout << "New Person Recent Frame:  " << newguy.getlastframeseen() << std::endl;
    std::cout << "New Person Recent history bottom:  " << newguy.getrecenthistory().bottom << std::endl;
    int place = assignID - 1;
    if (allthePeople->size() > place)
    {
        //assuming places starts from 1 to vector's size.
        (*allthePeople)[place] = newguy;
    }
    else
    {
        allthePeople->push_back(newguy);
    }
}

assign表示替换向量的全部内容。

假设你想把每个人都放在一个特定的地方。然后,您可以更好地使用operator[]将值放在您想要的位置,而不是使用assign。你需要有合适大小的向量。

if (allthePeople->size() >= place )
{
    //assuming places starts from 1 to vector's size.
    (*allthePeople)[place - 1] = newguy;    
}