与将新内容分配给向量的指针斗争
Struggling with pointers to Assign new contents to a vector
我要做的是将类的实例添加到向量的特定索引中。这个索引可以是最初不存在的,也可以是一个已被清除的现有索引,并且正在向该位置写入一个新的类实例。
下面是我一直用来尝试将这些实例写入向量的函数,并在底部注释,您可以看到我尝试使用的其他两个方法,显然使用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;
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 调整大小后指向元素值的指针unordered_map有效?
- 正在将指针转换为范围
- 使用指向成员的指针将成员函数作为参数传递
- 将OpenCV C++重写为EmguCV C#-如何使用指针
- 与将新内容分配给向量的指针斗争