使用结构的全局向量
我正在尝试全局声明并初始化一个结构向量。我的代码如下:
Struct creation (in header file vsystem.h)
struct var {
string name;
float value;
};
Variable (in source file vsystem.cpp)
#include <string>
#include <vector>
vector <var> varList;
这两个 # 都包括
和
。我也尝试过
vector <var> varList ();
但这也不起作用。我的错误是
expected constructor, destructor, or type conversion before '<' token
附带说明,我的 setVar
函数触发了错误:
Multiple markers at this line
- 'string' was not declared in this scope
- expected primary-expression before 'float'
- initializer expression list treated as compound
expression
- expected ',' or ';' before '{' token
代码:
int setVar(string varName, float value){
// Check to see if varName already exists
varExists = false;
for (int i=0; i<varList.size(); i++){
if (varList[i].name == varName){
varExists = true;
return ERR_VAR_EXISTS;
}
}
// Good! The variable doesn't exist yet.
var tempVar ();
var.name = varName;
var.value = value;
varList.push_back(tempVar);
return 0;
}
请帮忙!
我正在 Mac 10.6.7 上运行带有 G++ 编译器的 Eclipse Helios Service Release 2。
I am trying to globally declare – and initialize – a vector of structs. My code is the following:
Struct creation (in header file vsystem.h)
struct var {
string name;
float value;
};
Variable (in source file vsystem.cpp)
#include <string>
#include <vector>
vector <var> varList;
Both of those # include <string>
and <vector>
. I have also tried
vector <var> varList ();
But that doesn't work either. My error is
expected constructor, destructor, or type conversion before '<' token
On a side note, my setVar
function is triggering an error:
Multiple markers at this line
- 'string' was not declared in this scope
- expected primary-expression before 'float'
- initializer expression list treated as compound
expression
- expected ',' or ';' before '{' token
Code:
int setVar(string varName, float value){
// Check to see if varName already exists
varExists = false;
for (int i=0; i<varList.size(); i++){
if (varList[i].name == varName){
varExists = true;
return ERR_VAR_EXISTS;
}
}
// Good! The variable doesn't exist yet.
var tempVar ();
var.name = varName;
var.value = value;
varList.push_back(tempVar);
return 0;
}
Help please!
I am running Eclipse Helios Service Release 2 with G++ compiler on Mac 10.6.7.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
vector
位于std
命名空间中。您需要在声明中将其限定为std::vector
:(或者,您可以使用 using 声明,
using std::vector;
,如果您真的讨厌 < code>std::。)对于
string
类似;它需要被限定为std::string
。 C++ 标准库中的所有名称都位于std
命名空间中,除了 (a) 宏和 (b) 旧版 C 头文件中的名称(以 结尾的名称) .h)vector
is in thestd
namespace. You need to qualify it asstd::vector
in your declaration:(Alternatively you could use a using declaration,
using std::vector;
, if you really hate thestd::
.)Similarly for
string
; it needs to be qualified asstd::string
. All of the names in the C++ Standard Library are in thestd
namespace except (a) those that are macros and (b) those that are in the legacy C headers (the ones that end in .h)