简体   繁体   English

接受任何 STL 容器并创建指向其元素的指针向量的模板类 (C++)

[英]Template class that accepts any STL container and creates a vector of pointers to its elements (C++)

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:传递“Hello”然后尝试使用 for-cycle 打印它会导致:

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!任何帮助,将不胜感激!

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

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 .你不应该那样做。 . . . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM