矢量函数"push_back"不断将值重写到内存中的同一插槽
vector function "push_back" keeps rewriting the value to the same slot in memory
std::vector的push_back方法没有将第二个控制台输入放在v[1]插槽中,它一直覆盖它在v[0]
我试图寻找其他答案,但代码和答案对我来说太复杂了,我试图保持简单(但我尝试使用指针,只是得到了一堆错误)
我的方法:
vector<string> createtable(std::vector<std::string> v, std::string insertedstr) {
std::vector<std::string> vcreate;
vcreate.push_back(insertedstr + " ");
return vcreate;
}
主: int main()
{
int option;
std::string insertedstr;
std::vector<std::string> v;
cin >> insertedstr;
v = createtable(v, insertedstr);
for (int i = 0; i <=v.size(); i++) {
cout << v[i] << endl;
}
cin >> insertedstr;
v = createtable(v, insertedstr);
for (int i = 0; i <= v.size(); i++) {
cout << v[i] << endl;
}
return 0;
}
编辑:我想最终为这个写一个菜单,所以我想有一个无限数量的push_backs,所以只是在主程序中调用v.p ash_back对我来说是行不通的
如果有人能帮忙就太好了。
在每次调用createTable
时创建一个新的vector
,而不是重用现有的vector
;你不是不断地插入v[0]
,你不断地用一个只有一个元素的全新向量替换v
。对createTable
的第二个调用可能只是对v.push_back(insertedString);
的直接调用。
或者,删除vcreate
声明并实际使用传递到函数中的v
(这仍然是浪费,因为它不断地复制和替换vector
s,而不是直接推送到现有的,但它至少在逻辑上是正确的)。
您实际上从未将第二个输入写入任何内容。Push_back只被调用一次(在v = createtable(v, insertedstr);
调用的函数中),所以它只包含一个值。您需要实际调用push_back,并使用第二个应该进入vector的值。
vector<string> createtable(std::vector<std::string> v, std::string insertedstr) {
//std::vector<std::string> vcreate; // Not required
v.push_back(insertedstr + " ");
return v;
}
这个函数有问题。您每次都创建新的矢量vcreate
,而不是使用传递的矢量v
。所以每次都会有一个大小为1的新向量
相关文章:
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 升压信号2将插槽传递到成员功能以断开连接
- 为什么 connect() 函数看不到插槽?
- 使用std::bind将Qt信号连接到插槽
- 为什么在qt c++中找不到我的插槽?
- 将QPush按钮::单击信号到插槽时出错
- 如何将信号连接到类的所有实例的插槽
- Qt转发插槽/连接插槽到插槽?
- QT5 C 信号到QML插槽不起作用
- Qt无法手动连接到任何插槽(UI编辑器)
- 将一个对象的所有QT信号动态映射到一个插槽
- 如何将 QAction 从 QMenu 传递到 Qt 插槽
- 将所有对象信号连接到单个插槽
- 可以将多个信号连接到单个插槽
- 是否可以在没有接收器实例的情况下将信号连接到静态插槽
- QSignalManager-无法将多个信号连接到一个插槽
- 矢量函数"push_back"不断将值重写到内存中的同一插槽
- Qt:将多个输入部件与valueChanged(int)信号连接到单个插槽
- 我如何知道是否分配了内存插槽
- 如何通过QSignalMapper或其他方式从QMenu传递QString到Qt插槽