Cush
Cush

Reputation: 67

Passing a vectored struct into a function

I'm having trouble on how to call my function and I've searched thoroughly for over an hour now and just can't seem to find the answer.

Example code:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

struct student
{
    string first
    string last
}

void lookup_student(vector <student> *classes);

int main()
{
    vector <student> classes;    
    //put stuff here that fills up vector and such    
    lookup_student(&classes);    
    return 0;
}

void lookup_student(vector <student> *classes)
{
    cout << classes[0].first;
}

I just made this up on the spot since my current program has around 300 lines at the moment and this example explains exactly what I need. I'm sure either I'm declaring the struct vector wrong in the function or else I'm doing it wrong in main. Any help would be greatly appreciated.

The error message it gives me is that std::vector <student> has no member named first.

Upvotes: 2

Views: 52

Answers (2)

ravi
ravi

Reputation: 10733

You can use references for easier manipulation if you are facing difficulty with pointers:-

void lookup_student(const vector <student>& classes)
{
    //classes[i].first
}

and call it like

lookup_student(classes);

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117946

You have to dereference the pointer

cout << (*classes)[0].first;

I would recommend passing the vector as a const reference though, then you can use it the same way as you had it

void lookup_student(vector<student> const& classes)
{
    cout << classes[0].first;
}

Then you would just pass the vector as

int main()
{
    vector<student> classes;    
    //put stuff here that fills up vector and such    
    lookup_student(classes);    
    return 0;
}

Upvotes: 2

Related Questions