返回給定迭代器作為參數的適當類型的STL容器[重復]

[英]Returning an STL Container of the Appropriate Type given Iterators as Parameters [duplicate]


This question already has an answer here:

這個問題在這里已有答案:

I would like to write a template function that takes as its arguments two iterators of some STL container, First and Last, and returns an STL container of containing (a copy of) those elements between the two iterators that match some criteria. In other words, I want something like:

我想編寫一個模板函數,它將一些STL容器的兩個迭代器First和Last作為其參數,並返回一個STL容器,其中包含符合某些條件的兩個迭代器之間的那些元素(的副本)。換句話說,我想要一樣的東西:

template <typename Type>
Type Foo(Type::iterator First, Type::iterator Last)
{
    Type Result;
    for (Type::iterator i = First; i != Last; i++)
    {
        if (...)
        {
           Result.push_back(*i);
        }
    }
    return Result;
}

This however does not compile as the compiler says that "Type::iterator is not a type" (I call it with std::vector<double>).

然而這並沒有編譯,因為編譯器說“Type :: iterator不是一個類型”(我用std :: vector 調用它)。

Am I simply getting the syntax wrong? Or am I doing this completely the wrong way?

我只是簡單地弄錯了語法?或者我完全以錯誤的方式做這件事?

Thank you.

3 个解决方案

#1


1  

Try to use

嘗試使用

typename Type::iterator

#2


3  

With:

template <typename Type>
Type Foo(typename Type::iterator First, typename Type::iterator Last)

You cannot deduce Type (and there may have several possibilities anyway).
(You have to call it this way Foo<Container>(first, last))

你不能推斷出類型(並且可能有多種可能性)。 (你必須這樣稱呼Foo (第一個,最后一個))

You may create a type traits to do the job; something like:

你可以創建一個類型特征來完成這項工作;就像是:

template <typename T> struct get_container;

template <typename T*>
struct get_container<T*>
{
    typedef std::vector<T> type;
};

template <typename T>
struct get_container<std::list<T>::iterator>
{
    typedef std::list<T> type;
};

// And so on: care of possible conflict.

And then you have:

然后你有:

template <typename It>
typename get_container<It>::type Foo(It First, It Last)
{
    typename get_container<It>::type Result;
    for (It it = First; it != Last; ++it) {
        if (...) {
           Result.push_back(*it);
        }
    }
    return Result;
}

#3


1  

template <typename Container, typename InputIterator>
Container Foo(InputIterator First, InputIterator Last)
{
  using namespace std;
  Container Result;
  copy_if(First,Last, back_inserter(Result),pred)
  return Result;
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2014/02/04/72f2e130233a5624f41d146e5794bf52.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com