我正在尝试使用一个将结构作为参数的函数。
/**
* @param chunk A vector of C-style structs to hold the samples.
* @param timestamps A vector to hold the time stamps.
* @return True if some data was obtained.
*/
template<class T> bool the_function(std::vector<T> &C, std::vector<double> ×t){
T sample;
C.clear();
timest.clear();
while (double ts=other_function(sample,0.0)) {
C.push_back(sample);
timest.push_back(ts);
}
return !chunk.empty();
}
在一个示例(效果很好)中,该结构定义了一个固定大小的列表/vector (我不知道哪个是正确的)。
using namespace std
struct sample {
float d[64];
};
int main(int argc, char* argv[]) {
// Some stuff is made
vector<sample> result;
vector<double> ts;
if (double timest = the_function(result, ts)){
cout << timest << endl;
}
return 0;
}
但我想使用相同的函数,列表大小为 n 我可以选择。
我尝试向结构添加一个参数以允许我选择大小:
template <int T>
struct channels {
float d[T];
};
为了使用它,我在示例中使用了它:
const int n = function_count();
// function_count is a function from a class that return an int
vector<channels<n> > result;
vector<double> ts;
但是我在声明结果的那一行遇到了错误:
错误:“n”的值在常量表达式中不可用
我试过
const int n = 64;
它起作用了,所以我认为 function_count 有所不同,但 function_count 只返回一个 int。
那么我必须使用另一种结构吗?如何创建可与函数定义的参数一起使用的结构?
编辑
我想在不修改function_count
和the_function
的情况下找到解决方案,因为我没有制作这两个函数。
我尝试只使用 vector 来声明 result
,编译工作正常,但是当它尝试使用它时,我遇到了错误:Got an exception: An argument was incorrectly指定。
最佳答案
std::vector
的大小是自动调整的,即它的大小可以根据需要增加或减少。因此,只需创建适当类型的 vector 即可。
- 添加元素使用
std::vector
的函数void push_back (const value_type& val);
- 要删除元素,请使用
std::vector
的函数void pop_back();
您还可以创建一个设置了初始大小的 vector 。例如,下面将 vector vec
的大小设置为 5:
std::vector<float> vec(5);
关于以列表长度作为参数的 C++ 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845350/