使用结构的全局向量

时间:2011-04-30 03:35:51

标签: c++ eclipse vector struct

我正在尝试全局声明 - 并初始化 - 结构的向量。我的代码如下:

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;

这两个# include <string><vector>。我也试过

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.

1 个答案:

答案 0 :(得分:3)

vector位于std命名空间中。您需要在声明中将其限定为std::vector

std::vector <var> varList;

(或者你可以使用使用声明using std::vector;,如果你真的讨厌std::。)

同样适用于string;它需要被限定为std::string。 C ++标准库中的所有名称都在std命名空间中,除了(a)宏和(b)遗留C头中的那些(以 .h <结尾的那些) /强>)