hello, I am having trouble figuring out the proper syntax to pass a vector of integers (or strings, chars, etc) to a method of a class without getting compile errors. Here is a concise version of what I am trying to do:
Can someone please tell me what I need to do to get this code working correctly? As you can see, I just want to print the values (100 and 101) that are in the vector from inside the class method. I have looked around on this forum and others and followed advice given to other people who have asked this same question and still cannot get this to work so I decided it would be best to post my own code to see if maybe someone could give me better insight. Thanks for any help, this has been a real head scratcher!
You need to #include <vector> in the header file. Notice also that you need to use the fully-qualified name for the std::vector class in the header file. (Don't use usingnamespace std;.)
employ.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#ifndef _employ_
#define _employ_
#include <vector>
class Employ
{
public:
void Insert(std::vector<int>& input);
private:
int whatever;
};
#endif
Also, you'll need to make sure that there are two elements in the vector to modify before you try accessing them. There are two ways to fix it:
Method 1: use push_back() to append elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <vector>
#include "employ.h"
int main()
{
usingnamespace std;
Employ Test_Object;
vector<int> test; // length == 0
test.push_back( 100 ); // append an element to the vector (length == 1)
test.push_back( 101 ); // append another element (length == 2)
Test_Object.Insert(test);
return 0;
}
Method two: construct with two elements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <vector>
#include "employ.h"
int main()
{
usingnamespace std;
Employ Test_Object;
vector<int> test( 2 ); // make a vector, starting with length = 2
test[0] = 100;
test[1] = 101;
Test_Object.Insert(test);
return 0;
}
I prefer to use push_back method over the array notation method. Reason being if I specify an index that goes beyond the range, I get error. If I use push_back, vector class implementation will always do the job and ensure my item is behind the last in the range without any invalid index.