3

我有这个功能:

set<int> Search(const _Type & hayHeap) const {
        set<int>myset;
        for (vector<typename>::const_iterator i = needle.begin(); i != needle.end(); ++i) {
            cout << (*i) << " ";
        }
        return myset;
    };

针的定义如下:vector<string> needle;

现在我需要创建另一个迭代器,它将遍历hayHeap. 但问题是,我不知道它会是什么类型。它也可以是单个stringvectorof <int>/ <string>。所以当有 a 时string,它只迭代一次,如果有一些向量它迭代(myVector.count()-1)-times。如何使这种类型独立的迭代器?

4

2 回答 2

2

在 C++03 中:

template <typename C>
set<int> Search(const C& hayHeap) const {
    set<int>myset;
    for (typename C::const_iterator i = needle.begin(); i != needle.end(); ++i) {
        cout << (*i) << " ";
    }
    return myset;
};

在 C++11 中:

template <typename C>
set<int> Search(const C& hayHeap) const {
    set<int>myset;
    for (auto& i : needle) {
        cout << i << " ";
    }
    return myset;
};

根据您的实际需要,您将替换inttypename C::value_type

于 2013-04-16T15:24:15.417 回答
1

好的,我想我现在明白你的问题了。我认为您正在寻找某种类型的功能。这种东西。

template<typename T>
struct my_selector {
    static void search(T& t) {
        cout << " Single string / int search" << endl;
        bool b = t == "needle";
        cout << b;
    }
};

template<typename T>
struct my_selector<vector<T>> {
    static void search(vector<T>& needle) {
        cout << " Vector search" << endl;
        for (typename vector<T>::const_iterator i = needle.begin(); 
                      i != needle.end(); ++i) 
        {
           cout << (*i) << " ";
        }
    }
};

int main() {


  typedef std::vector<std::string> _Type;  
  _Type needle(4,"s");
  // Search function is selected based on type of _Type.
  my_selector<_Type>::search(needle);


  // typedef string _Type;  
  // _Type needle = "needle";
  // // Search function is selected based on type of _Type.
  // my_selector<_Type>::search(needle);


}
于 2013-04-16T15:30:19.093 回答