簡體   English   中英

將結構向量傳遞給函數

[英]passing a vector of structs into a function

在程序中,頭文件中定義了以下結構:

\\structs.h
#include <vector>
using std::vector;
using namespace std;
struct cell
{
    double x;
    vector<int> nn;
};

在單獨的源文件中,我定義了函數:

\\functions.cpp
# define _CRT_SECURE_NO_DEPRECATE
# include <stdio.h>
# include <iostream>
# include <math.h>
# include <vector>
# include "structs.h"
using namespace std;

void initial_position(vector<cell>& cluster, int n)
{
    cell tmp;
    for (int i = 0; i < n; i++)
    {
        tmp.x = 1;
        cluster.push_back(tmp);
    }
}

帶有頭文件:

//functions.h
# include <vector>
using std::vector;

void initial_position(vector<cell>& cluster, int n);

我希望在主腳本中調用此函數:

//main.cpp
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <vector>
#include "functions.h"
#include "structs.h"  
using namespace std;

int main()
{   
    vector <cell> cluster;
    int n = 100;
    initial_position(cluster,n);
    return 0;
}

但出現以下錯誤:

functions.h(4):錯誤C2065:'cell':未聲明的標識符

functions.h(4):錯誤C2923:'std :: vector':'cell'不是參數'_Ty'的有效模板類型參數

functions.h(4):錯誤C3203:'分配器':未專用的類模板不能用作模板參數'_Alloc'的模板參數,應為實型

main.cpp(14):錯誤C2664:'void initial_position(std :: vector&)':無法將參數1從'std :: vector>'轉換為'std :: vector&'

錯誤的根源是什么? 一切似乎都定義清楚。

#include "structs.h" 

進入functions.h並使用include-guards保護structs.h和functions.h

#pragma once

如果可供使用的話。

#include "structs.h" 

進入functions.h中,因為在functions.h中,編譯器不知道什么是單元格。

只是交換

#include "functions.h"
#include "structs.h"  

#include "structs.h"  
#include "functions.h"

由於cell是在structs.h中聲明的,而在functions.h中是必需的

或者更好的是,在functions.h中包含structs.h

您也不應在標題中使用命名空間std,這是一種不好的做法。 它可能會導致難以發現的錯誤,例如, 為什么“使用命名空間標准”被認為是不良做法?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM