int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;
我試圖找到向量中元素的索引。沒關係iterators
,但我想要它作爲int
。我該怎麼做?將迭代器轉換爲int
int i;
vector<string> names;
string s = "penny";
names.push_back(s);
i = find(names.begin(), names.end(), s);
cout << i;
我試圖找到向量中元素的索引。沒關係iterators
,但我想要它作爲int
。我該怎麼做?將迭代器轉換爲int
您可以使用std::distance
這一點。
i = std::distance(names.begin(), std::find(names.begin(), names.end(), s));
雖然你可能想檢查一下你的索引是否超出界限。
if(i == names.size())
// index out of bounds!
雖然在使用std :: distance之前用迭代器來做這件事可能會更清楚。
std::vector<std::string>::iterator it = std::find(names.begin(), names.end(), s);
if(it == names.end())
// not found - abort!
// otherwise...
i = std::distance(names.begin(), it);
嘗試
i = (find(names.begin(), names.end(), s) - names.begin());
編輯: 雖然你應該考慮使用矢量:: size_type的,而不是一個int。
std::vector<string>::iterator it = std::find(names.begin(), names.end(), s);
if (it != names.end()) {
std::cout << std::distance(names.begin(), it);
} else {
// ... not found
}
假設,我提出有關代碼:
using std::vector;
using std::cout;
using std::string;
如果我的假設是正確的,那麼你就可以find
的vector
的開始和iterator
(基本上是索引到的distance
vector
上,你可以找到這樣的元素):
using std::distance;
是這樣的...
vector<string>::iterator i = find(names.begin(), names.end(), s);
if (i != names.end())
{
cout << "Index " << std::distance(names.begin(), i);
}
else
{
cout << s << "not found";
}
你可以解引用你的迭代
int i = *name;
它使編譯器錯誤,因爲我是int而不是迭代器。 – thetux4 2011-05-26 09:31:11
@ thetux4:它不應該這樣做。當你減去兩個迭代器時,你應該得到一個差異類型,對於'std :: vector :: iterator'是一個整數類型。 –
2011-05-26 09:33:20
是的,我知道;)這就是爲什麼你應該使用我的線,而不是你的。 find()返回一個迭代器,並從該迭代器中減去names.begin()可以得到一個向量 :: size_type。 (一個無符號的整數類型 - 可能類似unsinged長) –
iolo
2011-05-26 09:33:39