如何在字符串向量中获取某个元素的位置,以将其用作int向量中的索引?


99

我正在尝试获取的向量中元素的索引strings,以将其用作另一int类型的向量中的索引,这可能吗?

例:

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_nameNames矢量,在访问某些元素使用它Numbers载体。这样我可以说:

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是string类型的!



您应该签出std :: map或std :: unordered_map。
Etherealone

Answers:


158

要知道一个向量在迭代器中指向该元素的位置,只需v.begin()从迭代器中减去:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

现在,你需要检查posNames.size(),看它是否是界限或不出来:

if(pos >= Names.size()) {
    //old_name_ not found
}

向量迭代器的行为类似于数组指针;您对指针算法了解的大多数知识也可以应用于向量迭代器。

从C ++ 11开始,您可以使用std::distance迭代器和指针代替减法:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

抱歉,我看不到@Bob__的评论,也许删除了?我想知道为什么ptrdiff_t有更好的方法,size_t因为ptrdiff_t 这样会引发有符号和无符号整数之间的比较警告
Hiraku

3
@Hiraku他确实删除了他的评论。他建议使用,ptrdiff_t因为它使您可以将任意一对迭代器之间的距离存储到同一容器中,即使结果为负。如果使用,size_t则必须注意不要从较小的迭代器中减去较大的迭代器。
dasblinkenlight

更准确地说,您应该添加“ #include <algorithm>”(用于使用std :: find)。问题的作者也省略了此“包含”。
Grag2015 '18

92

如果需要索引,可以std::find与结合使用std::distance

auto it = std::find(Names.begin(), Names.end(), old_name_);
if (it == Names.end())
{
  // name not in vector
} else
{
  auto index = std::distance(Names.begin(), it);
}

8
为什么不使用const-iterators?
丹尼

-1

我是初学者,所以这里是初学者的答案。for循环中的if给出i,然后可以使用它,但是需要使用它,例如另一个向量中的Numbers [i]。多数是出于示例的考虑,for / if确实说明了一切。

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.