简体   繁体   中英

passing a vector of structs into a function

In a program the following struct is defined in a header file:

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

In a separate source file I define the function:

\\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);
    }
}

with a header file:

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

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

I wish to call this function in the main script:

//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;
}

but get the following errors:

functions.h(4): error C2065: 'cell': undeclared identifier

functions.h(4): error C2923: 'std::vector': 'cell' is not a valid template type argument for parameter '_Ty'

functions.h(4): error C3203: 'allocator': unspecialized class template can't be used as a template argument for template parameter '_Alloc', expected a real type

main.cpp(14): error C2664: 'void initial_position(std::vector &)': cannot convert argument 1 from 'std::vector>' to 'std::vector &'

What is the source of the errors? it all seems to be well defined.

Put

#include "structs.h" 

into functions.h and protect both structs.h and functions.h with include-guards, eg

#pragma once

if available.

add

#include "structs.h" 

into functions.h since in functions.h compiler doesn't know what cell is.

Just swap

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

with

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

Since cell is declared in structs.h and is needed in functions.h

Or better yet, include structs.h in functions.h

You should also not place using namespace std in a header, that is bad practice. It can cause some nasty hard to find bugs, see eg Why is "using namespace std" considered bad practice?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM