c++在单独的函数中定义向量
c++ define vector in separate function
我想在一个可能被多个程序使用的函数中定义一个具有静态内容的向量。然而,我面临着一些问题。
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;
相关文章:
- 自己的自定义向量类. 内存重新分配
- C++类中的类作为自定义向量(如何初始化?
- 在C++中使用带有自定义向量的迭代器
- 创建自定义向量类错误
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?
- 如何为我的自定义向量类实现类似 vector.insert 的方法
- 如何在没有参数列表的情况下定义向量无效使用模板名称 std::vector
- 将 boost odeint 与 std::map 和自定义向量空间代数一起使用时,没有可行的重载'='
- Push_back类定义向量的函数
- 自定义向量类的解构函数
- c++在单独的函数中定义向量
- 定义向量元素的破坏顺序是否合理
- vector.erase 和 std::remove 在自定义向量上
- 在自定义类中定义向量
- C++11 initializer_list构造函数,带有自定义向量类的头和cpp文件
- 如何在<ifstream> C++ 类中定义向量
- 为自定义向量类中的特定元素指定一个值.作为a[5]=3 C++
- 重载自定义向量类中的和运算符
- 如何在C++中定义向量<boost::mutex>?
- 在自定义向量类中调用了错误的构造函数