简体   繁体   English

如何从STL容器实例中获取元素类型?

[英]How to get element type from STL container instance?

I know about value_type, key_type... but they operate on types, not on instances. 我知道value_type,key_type ......但它们是在类型上运行,而不是在实例上运行。 I tried stuff like : 我试过像这样的东西:

std::set<uint64_t> mySet;   

decltype (mySet)::value_type pos;

But it doesnt work. 但它不起作用。

EDIT: I use VS 2010. 编辑:我使用VS 2010。

EDIT2: the prupose of this code was to get a type to give it to boost::lexical_cast<> is there a workaround that enables that ? EDIT2:这段代码的目的是得到一个类型来赋予它boost :: lexical_cast <>是否有一个解决方法可以实现? I want something like this: 我想要这样的东西:

   mySet.insert(boost::lexical_cast<decltype(mySet)::value_type>(*it));
  // it is a iterator in vector of strings

EDIT3 : this works: 编辑3:这有效:

mySet.insert(boost::lexical_cast<decltype(mySet)::value_type>(*it));

decltype (mySet)::value_type is correct. decltype (mySet)::value_type是正确的。 Make sure you have C++11 mode enabled in your compiler. 确保在编译器中启用了C ++ 11模式。 If you have, then it's a compiler bug. 如果你有,那么这是一个编译器错误。

A possible workaround involves using the identity metafunction: 可能的解决方法涉及使用标识元函数:

template <typename T>
struct identity { typedef T type; };

identity<decltype(mySet)>::type::value_type pos;

I'd do it the other way around: 我会以相反的方式做到这一点:

typedef std::set<uint_least64_t> set_type;
set_type mySet;
set_type::value_type pos;

Here is a simple example of print method that prints elements of a priority queue: 以下是打印优先级队列元素的print方法的简单示例:

template<typename T> void print_queue(T& queue) {
    while (!queue.empty()) {
        std::cout << queue.top() << " ";
        queue.pop();
    }
    std::cout << '\n';
}

The problem is, that after printing of all elements the queue is empty. 问题是,在打印所有元素之后,队列是空的。 To restore the queue to original state we add vector container. 要将队列恢复到原始状态,我们添加了矢量容器。 The type of queue elements is deduced from the queue: 队列元素的类型是从队列中推导出来的:

template<typename T> void print_queue(T& queue) {
    std::vector<T::value_type> vec;
    while (!queue.empty()) {
        std::cout << queue.top() << " ";
        vec.push_back(queue.top());
        queue.pop();
    }
    std::cout << '\n';
    for (auto & v : vec) {
        queue.push(v);
    }
}

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

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