How to reference elements of a returned vector
Jun 17, 2018 at 6:53am Jun 17, 2018 at 6:53am UTC
I have a class that returns a vector.
1 2 3
void test(vector<double > v){
return v
}
I don't understand how I access the individual elements of the vector when I call test. Is the syntax something like "test(myvector)[0]"? I realize this is probably a really dumb question, but I've been struggling with it for a while.
Jun 17, 2018 at 7:25am Jun 17, 2018 at 7:25am UTC
Normally you pass a STL container by reference or const reference since they can be expensive to copy.
You pass a vector like any other variable.
1 2 3 4 5 6 7 8 9 10 11
void test(vector<int > & v)
{
// use v
}
int main()
{
vector<int > nums = {1, 2, 3};
test(nums);
}
If you want to return a vector from a function you need to specify it as the return type.
1 2 3 4 5 6 7 8 9 10 11
vector<int > test2()
{
vector<int > v = {1, 2, 3};
return v;
}
int main()
{
vector<int > nums = test2();
// use nums
}
Topic archived. No new replies allowed.