c++ - 使用结构的全局 vector

标签 c++ eclipse vector struct

我正在尝试全局声明并初始化一个结构 vector 。我的代码如下:

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。

最佳答案

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

std::vector <var> varList;

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

string类似;它需要被限定为 std::string。 C++ 标准库中的所有名称都在 std 命名空间中,除了 (a) 宏和 (b) 遗留 C header 中的名称(以 结尾的名称) .h)

关于c++ - 使用结构的全局 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5839310/

相关文章:

c++ - std::vector 结构的 MPI BCast(广播)

c++ - 使用 std::vector.push_back() 时出现错误 C2280

C++ 类 : create copy of "this" class within member function

c++ - CMAKE_CXX_CLANG_TIDY : avoid clang-diagnostic-error interrupting build

eclipse - 在 Debug模式下启动tomcat 6?

java - 如何告诉 Maven 包含 jar 依赖项,而不是 Eclipse 中的子项目源目录?

c++ - 使用 C++ 进行简单的字符串解析

c++ - 在 C++、Linux 中获取像素的颜色

java - 如何从 Eclipse 运行任意服务器软件?

haskell - Haskell 的 `Data.Vector.Mutable.unsafeNew` 是否会将内存清零?