2016-02-29 87 views
0

爲什麼此代碼給我一個錯誤?不符合運營商[]

#include<iostream> 
#include<string> 
#include<vector> 
using namespace std; 
string k; 
vector<string> f; 
int main() 

{ 
    string k; 
    while (cin >> k) { 
     char l = '3'; 
     cin >> k; 
     for (auto &v : k) { 
      if (v == 'e') 
       v = l; 
      if (v == 'i') 
       v = '1'; 
      if (v == 'z') 
       v = '2'; 
     } 

     f.push_back(k); 
    } 
    auto r = f.begin(); 
    auto s = f.end(); 
    while (r != s) { 
     string j = f[r]; 
     cout << j; 
     ++r; 
    } 
    return 0; 
} 

我試着編譯它並編輯它很多次,但我總是得到這個錯誤。 所以我嘗試使用不同類型的迭代器,但不能做得更厲害。 有沒有人有解決這個問題的建議? 這將是一個leet文本生成器

+2

當'r'是一個迭代器時,你不通過'f [r]來訪問元素。取而代之的是使用'* r' – user463035818

回答

1

由於r是一個迭代器,您可以像使用它的指針那樣使用它,而不像數組索引。所以f[r]應該是*r

string j = *r; 
2

你想將兩種不同的方式在std::vector訪問一個元素,使用迭代器,並使用下標運算符。

如果您想使用下標操作符,你有一個有效的索引到載體中,調用它,如:

std::string s = v[1]; // get the second element of the vector 

如果你想使用迭代器,你會做這樣的代替:

auto it = v.begin(); 
std::string s = *it; // get the element referred by the iterator it