Returning list without forcing the data structure

Hi
I have run in to this problem a few times and im never really sure what to do:

Basically, sometimes, i have a function that needs to return a selection of objects. Usually i will just return the objects in the form of a vector.

But the problem is that i dont want to force the caller of the function to use a vector if they dont want to.

For example: what if the caller wanted to have the objects in a linked list instead? then they would be forced to spend time converting the two data structures.

The only solution i can think of, is to create a function for every single data structure, like this: GetObjects_Vector(), GetObjects_LinkedList(), GetObjects_Que(), etc. But this is obviously not really possible to do for every single data structure that exists.

Is there a better solution?
Last edited on
Sounds like a template is what you need. Something like this:
1
2
3
4
5
6
template <typename TYPE>
void getObjects(TYPE& container)
{
  // add items to the end of the container like this
  container.insert( container.end(), value_to_insert );
}


The user calls it with whatever container type they feel like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <vector>
#include <list>

using std::list;
using std::vector;

template <typename TYPE>
void getObjects(TYPE& container)
{
  // example, adding int values to a container<int>
  container.insert( container.end(), 7 );
  container.insert( container.end(), 12 );
}

int main()
{
    vector<int> vec;
    getObjects(vec);
    std::cout << vec[0] << '\n';
    
    list<int> lis;
    getObjects(lis);
    std::cout << lis.back();
}


As can be seen here - https://en.cppreference.com/mwiki/index.php?title=Special%3ASearch&search=insert - a great many of the standard containers support an insert function (and an end function). You would be able to use the template above with any container that supports an insert function.
Last edited on
Topic archived. No new replies allowed.