c++在单独的函数中定义向量

c++ define vector in separate function

本文关键字:定义 向量 函数 单独 c++      更新时间:2023-10-16

我想在一个可能被多个程序使用的函数中定义一个具有静态内容的向量。然而,我面临着一些问题。

main.cpp看起来是这样的:

#include <iostream>
#include <boost/assign/std/vector.hpp>
using namespace std;
using namespace boost::assign;
int main (int argc, char* argv[]) {
  vector< int > v;
  v +=   3,5,1;
  for (int i=0; i<v.size(); i++) {
   cout << "v: " << i << " " << v[i] << endl;
  }
}

这是有效的,我得到一个输出:

v: 0 3
v: 1 5
v: 2 1

然而,如果我试图将矢量定义放入一个单独的文件中,它是不起作用的。

main.cpp

#include <iostream>
#include "vector_test.hpp"
using namespace std;
int main (int argc, char* argv[]) {
  vector< int > v;
  for (int i=0; i<v.size(); i++) {
    cout << "v: " << i << " " << v[i] << endl;
  }
}

vector_test.hpp:

#include <boost/assign/std/vector.hpp>
#include <stdio.h>
using namespace std;
using namespace boost::assign;

static std::vector<int> v;
v +=   3,5,1;

试图编译它给了我一个错误:

'v' does not name a type

qt的创建者也告诉我:

expected a declaration

我该如何解决这个问题?

一种方法是让函数返回对静态实例的引用:

const std::vector<int>& get_magic_vector()
{
  static std::vector<int> v{3, 5, 1};
  return v;
}

然后

for (auto i : get_magic_vector())
  std::cout << i << " ";

在其他文件中,您必须声明变量存在,但在另一个文件中定义。也就是说,在otherFile.cpp中,您在文件范围中放置以下行:

 extern std::vector<int> v;