我试图在向量中获取元素的索引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);
}
Run Code Online (Sandbox Code Playgroud)
现在,我想要得到的位置old_name的Names矢量,在访问某些元素使用它Numbers载体.所以我可以说:
Numbers[position] = 3 ; // or whatever value assigned here.
Run Code Online (Sandbox Code Playgroud)
我试过用:
vector <string> :: const_iterator pos;
pos = (find(Names.begin(), Names.end(), old_name_))
Numbers[pos] = 3;
Run Code Online (Sandbox Code Playgroud)
但显然这不起作用,因为pos是字符串类型!
das*_*ght 156
要获取向量中元素的位置,知道指向元素v.begin()的迭代器,只需从迭代器中减去:
ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
Run Code Online (Sandbox Code Playgroud)
现在,你需要检查pos对Names.size(),看它是否是出界与否的:
if(pos >= Names.size()) {
//old_name_ not found
}
Run Code Online (Sandbox Code Playgroud)
向量迭代器的行为方式类似于数组指针; 您对指针算法的了解大多数也可以应用于向量迭代器.
从C++ 11开始,您可以使用std::distance迭代器和指针的减法代替:
ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
Run Code Online (Sandbox Code Playgroud)
jua*_*nza 88
如果你想要一个索引,你可以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);
}
Run Code Online (Sandbox Code Playgroud)