[英]Problem properly pushing 2D vector of structs (C++)
我在填充vector<vector<clickable> >
类型的vector<vector<clickable> >
时遇到麻烦。 只要push_back发生在与变量声明相同的函数中,编译器似乎可以将vector<clickable>
推回到它上面,但是当变量在.h文件中声明时它不允许它push_back在类的另一个函数中执行。
在下面的示例中,循环应该完全相同,除了在同一函数中声明的vector<vector<clickable> >
上调用push_back,而另一个调用.h文件中声明的push_back。
什么有用的例子(这是来自main函数,但它适用于任何函数。):
vector<vector<clickable> > clicks;
for(int i = 0; i < 10; i++){
vector<clickable> click;
for(int j = 0; j < 10; j++){
click.push_back(clickable(Rect(Point(50,50),5,10),"blar"));
}
clicks.push_back(click);
}
什么不起作用的例子:
Gui.h:
#include <vector>
//...
struct clickable {
Rect rect;
string msg;
bool visible;
clickable(Rect rectangle, string message){
rect = rectangle;
msg = message;
visible = true;
}
};
//...
class Gui{
public:
//...
void load_environment();
//...
private:
vector<vector<clickable> > ship;
//...
}
Gui.cpp:
#include "Gui.h"
//...
void Gui::load_environment(){
for(int i = 0; i < 10; i++){
vector<clickable> click;
for(int j = 0; j < 10; j++){
click.push_back(clickable(Rect(Point(50,50),5,10),
"blar"));
}
ship.push_back(click);
}
}
//...
我认为这可能与我无法重载某些运算符有关,但实际上我什至不知道这是否是问题的原因,或者我应该重载什么。
编辑这是错误的文本:
Gui.cpp:47: error: no matching function for call to 'std::vector<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::allocator<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >::push_back(std::vector<clickable, std::allocator<clickable> >&)' /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h:602: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, _Alloc = std::allocator<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >]
该错误消息指出,实际上,它认为你想在矢量push_back
到实际上是一个vector<vector<string> >
而不是一个vector<vector<clickable> >
如您所期望。
您可能只需要进行干净的重建即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.