Gluing together parts to a vector arguement

In main I have the following variables:
1
2
3
int a;
vector<int> b;
vector <int> c;


I have given all of them values. I want to call a function f, int f(vector<int> v) {...}, with the three parts (a,b,c) glued together (the order doesn't matter) to form the vector v. But I'm not interested in keeping that vector outside f. One solution (just to show what I want to do) would be to create a new vector like this (note it has the order [b, c, a], but like I said it doesn't matter):

1
2
3
4
5
6
7
vector<int> temp;
temp = b;
for(int i = 0; i<c.size(); i++){
   temp.push_back(c[i]);
}
temp.push_back(a);
int x = f(temp);


However this looks real clumpsy and like I said Im not interested in keeping temp. I wonder if I can do this on one line, without creating a new vector. Something like (in principal):
f([a, b, c]).

Oh btw, what is the correct term for gluing together vectors like this?

/Peter
Last edited on
I don't think there is a way to do something like this. You could make your code shorter with vector::insert, though.
1
2
3
4
5
vector<int> temp;
temp.push_back(a);
temp.insert(temp.end(), b.begin(), b.end());
temp.insert(temp.end(), c.begin(), c.end());
int x = f(temp);
There is no one-line method outside of something you write yourself.

However, you may find the vector::insert() method useful:

1
2
3
4
5
6
7
8
9
10
11
12
int a;
vector <int> b;
vector <int> c;

int x;
{
  vector <int> v;
  v.push_back( a );
  v.insert( v.end(), b.begin(), b.end() );
  v.insert( v.end(), c.begin(), c.end() );
  x = f( v );
}

This is called concatenation.

Hope this helps.

[edit] Man, too slow... again... :-\ [/edit]
Last edited on
Thanks!

It's weird that u have to create a new variable like temp, because when I call f that vector is copied to v. So temp is never used after the call, not even in f.

Same question if I want to send parts of a vector. Suppose I have vector<int> a and want to call f with the last 10 elements of a (suppose a.size() > 10). Can this be done without creating a temp vector like below?

1
2
3
vector<int> temp;
temp.assign(a.end()-9, a.end());
f(temp)


I'm translating a matlab code and this is easy to do there. What bugs me are those extra dummy variables I need to create. Do I have to delete them to free the memory too?
To get a part of vector you can write f(vector(a.end()-9, a.end()))
You don't need to delete these temp variables, The memory will be freed on the next '}'. If you're worried about the memory usage, do what Duoas did: add { and } around the part where the temp is being used.
If you don't like how these variables look, you can write your own function, that joins several vectors.
Ok cool I'll try that :)! Thanks for the help!
Topic archived. No new replies allowed.