5

为什么这个简单的代码块无法编译

//using namespace std;
struct test {
    std::vector<int> vec;
};
test mytest;

void foo {
    mytest.vec.push_back(3);
}

int main(int argc, char** argv) {
   cout << "Vector Element" << mytest.vec[0] << endl;
   return 0;
}

我收到以下错误:

vectorScope.cpp:6:5: error: ‘vector’ in namespace ‘std’ does not name a type

vectorScope.cpp:11:6: error: variable or field ‘foo’ declared void

vectorScope.cpp:11:6: warning: extended initializer lists only available with -std=c++0x or -std=gnu++0x [enabled by default]

vectorScope.cpp:12:12: error: ‘struct test’ has no member named ‘vec’

vectorScope.cpp:12:28: error: expected ‘}’ before ‘;’ token

vectorScope.cpp:13:1: error: expected declaration before ‘}’ token

谢谢,

穆斯塔法

4

4 回答 4

8

您需要包含矢量头文件

#include <vector>
#include <iostream>

struct test {
    std::vector<int> vec;
};
test mytest;

void foo() {
    mytest.vec.push_back(3);
}

int main(int argc, char** argv) 
{
   foo();  
   if (!mytest.vec.empty())  // it's always good to test container is empty or not
   {
     std::cout << "Vector Element" << mytest.vec[0] << std::endl;
   }
   return 0;
}
于 2013-01-14T00:53:00.377 回答
5

如果您的代码示例完整,则您没有包含矢量标头或 iostream 标头。此外,您的 foo 函数在没有 () 参数的情况下被错误地声明:

#include <vector>
#include <iostream>

using namespace std;
struct test {
    std::vector<int> vec;
};
test mytest;

void foo()  {
    mytest.vec.push_back(3);
}

int main(int argc, char** argv) {
   cout << "Vector Element" << mytest.vec[0] << endl;
   return 0;
}

此外,您在索引 0 处下标一个空向量,这是未定义的行为。你可能想在这样做之前先调用 foo() ?

于 2013-01-14T01:06:31.370 回答
4

您缺少<vector>标题。

#include <vector>
于 2013-01-14T00:53:36.260 回答
1

请记住包含适当的文件:

#include <vector>
于 2013-01-14T00:53:16.320 回答