2014-10-11 42 views
6

有沒有一種方法可以在C++語法中縮短/簡化迭代器聲明。通常我會:更簡單的C++ STL迭代器實例化

vector<pair<string, int> > v; 
vector<pair<string, int> >::iterator i; 

我所期待的一些神奇的將:

vector<pair<string, int> > v; 
magic v::iterator i; 
+0

如果使用C++ 11,請檢查'auto'說明符。 – Macmade 2014-10-11 06:48:49

+1

如果您使用的是C++ 11,只需說'auto i(v.begin());'並且編譯器會推斷'i'的正確類型。 http://en.cppreference.com/w/cpp/language/auto – dgnuff 2014-10-11 06:49:54

回答

5

在C++ 11,您有三種選擇:

1. Typedef矢量實例化

typedef std::vector<std::pair<std::string, int>> Vp; 
Vp v; 
Vp::iterator i; 

2.使用decltype

std::vector<std::pair<std::string, int>> v; 
decltype(v)::iterator i; 

3.使用auto

std::vector<std::pair<std::string, int>> v; 
auto i = v.begin(); 

我想說的第三個選項是最常見的,習慣用法,但都是有效,第一個選項也適用於C++ 98。

+0

decltype是我尋找的魔法。但只可惜在C++ 11中。 – Waslap 2014-10-11 07:52:26

7

只需使用typedef混疊您vector<pair<string, int> >

typedef vector<pair<string, int> > Vp; // vector of pair 

然後,

Vp v; 

Vp::iterator i; 
0

C++ 11:

using v = vector<pair<string, int> >; 
using i = v::iterator; 

魔術:

v _v; 
i _i{ _v.begin() }; 
2

我使用typedef很多:

// vector of strings 
typedef std::vector<std::string> str_vec; 

// iterator 
typedef str_vec::iterator str_vec_iter; 

// constant iterator 
typedef str_vec::const_iterator str_vec_citer; 

// reverse iterator 
typedef str_vec::reverse_iterator str_vec_riter; 

// constant reverse iterator 
typedef str_vec::const_reverse_iterator str_vec_criter 

int main() 
{ 
    str_vec v = {"a", "b", "c"}; 

    // writable iteration 
    for(str_vec_iter i = v.begin(); i != v.end(); ++i) 
     i->append("!"); 

    // constant iteration 
    for(str_vec_citer i = v.begin(); i != v.end(); ++i) 
     std::cout << *i << '\n'; 

    // constant reverse iteration 
    for(str_vec_criter i = v.rbegin(); i != v.rend(); ++i) 
     std::cout << *i << '\n'; 
} 

某些容器是很常見的,我有自己的類型定義的我一直使用的個人頭文件(自然命名空間)。

但由於C++ 11的不那麼重要,因爲auto關鍵字的推斷類型爲你的:

for(auto&& i: v) 
    std::cout << i << '\n'; 
2

在C++ 11你可以寫:

decltype(v)::iterator