Home > Enterprise >  Template class that accepts any STL container and creates a vector of pointers to its elements (C )
Template class that accepts any STL container and creates a vector of pointers to its elements (C )

Time:05-24

I want to create a template class that accepts any standard library container (most importantly: vectors, and strings). This, so far is not a problem. However, I want to store a vector of pointers in this class and the pointers within this vector should each point to the individual elements of the accepted container.

My impression is that this would allow me to change the values in the original container (as long as their type, and the container size doesn't change), without touching the template class entity. So I would have a vector of pointers always pointing to my original container elements regardless of their values or what the original container's container-type was.

How could I achieve this? When I pass a string to my template class, and try to print each value my pointers are pointing to, I get a strange result. Passing "Hello" and then trying to print it with a for-cycle results in:

ello llo lo o

Seems to me like I'm not passing my original string char-by-char into the pointer vector.

Any help would be appreciated!

CodePudding user response:

You can try something like this:

#include <memory>
#include <type_traits>
#include <vector>

template<class Container>
auto
pointer_to_elements(Container&& container)
{
    using T = typename std::decay_t<Container>::value_type; // type of contained element
    std::vector<T*> ret;
    for (auto& element : container) {
        ret.push_back(std::addressof(element));
    }
    return ret;
}

It would probably be necessary to reject rvalue references for the parameter to avoid dangling pointers.

It can be used as such:

#include <iostream>
#include <string>

int main()
{
    std::string s = "hello";
    auto ptrs = pointer_to_elements(s);
    for (auto& ptr : ptrs) {
        std::cout << *ptr << '\n';
    }
}

This will print:

h
e
l
l
o

CodePudding user response:

Unfortunately your approach will most often not work.

Memory in containers may be reallocated. Without the chance for you to notice that. Then your pointer would show to indeterminate memory.

While you can write a program that seems to work, it will nmost likely fail.

You should not do that . . .

  • Related