问题描述
我试图在 strings
的向量中获取元素的索引,以将其用作 int
类型,这是否可能?
I am trying to get the index of an element in a vector of strings
, to use it as an index in another vector of int
type, is this possible ?
示例:
vector <string> Names;
vector <int> Numbers;
...
// condition to check whether the name exists or not
if((find(Names.begin(), Names.end(), old_name_)) != Names.end())
{ // if yes
cout <<"Enter the new name."<< endl;
cin >> name;
replace(Names.begin(), Names.end(), old_name_, name);
}
现在我想得到 old_name
向量中使用它来访问 Numbers
向量中的某个元素。所以我可以这样说:
Now I want to get the position of old_name
in the Names
vector, to use it in accessing certain element in Numbers
vector. So that I can say:
Numbers[position] = 3 ; // or whatever value assigned here.
我尝试使用:
vector <string> :: const_iterator pos;
pos = (find(Names.begin(), Names.end(), old_name_))
Numbers[pos] = 3;
但显然这不起作用,因为 pos
是类型字符串!
but obviously this doesn't work since pos
is of type string !
推荐答案
为了获得元素在向量中的位置,知道迭代器指向元素,从迭代器中减去 v.begin()
:
To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin()
from the iterator:
int pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
现在您需要检查 pos
code> Names.size()以查看它是否超出范围:
Now you need to check pos
against Names.size()
to see if it is out of bounds or not:
if(pos >= Names.size()) {
//old_name_ not found
}
向量迭代器的行为方式类似于数组指针;大多数你知道的指针算术也可以应用于向量迭代器。从C ++ 11开始,您可以使用代替迭代器和指针的减法。
Vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well. Starting with C++11 you can use std::distance
in place of subtraction for both iterators and pointers.
这篇关于如何获取字符串向量中的某个元素的位置,使用它作为ints向量中的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!