我正在使用c++内置的“列表”,我需要找到值“目标”的索引,在java中,有一个函数indexOf
可以解决此问题,在c++中是否有类似功能?
我尝试使用std::find()
,但它本身返回的是“目标”值而不是索引?但是我需要目标值的索引。
问题:我得到了一个目标值数组,一个列表,遍历目标数组,对于每个元素,在列表中找到其索引并打印索引,然后从列表中删除目标值并将其推到前面
target values [3,1,2,1] , list : 1->2->3->4->5
for i=0 target[0] = 3 , index in list = 2 <- print it
updated list 3->1->2->4->5
for i=1 target[1] = 1, index in list = 1 <- print it
updated list : 1->3->2->4->5
等等
最佳答案
std::list没有随机访问迭代器。您正在寻找的可能是对象的迭代器。
例如。,
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> l{1, 2, 3, 4, 5};
for (auto i: {3, 1, 2, 1})
{
auto it = l.begin();
for (auto index = 1; it != l.end(); it++, index++)
{
if (*it == i)
{
cout << "\n" << i << " is located at node " << index << endl;
l.splice(l.begin(), l, it);
cout << "Updated list: ";
for (auto i: l) { cout << i << " "; }
break;
}
}
}
return 0;
}
关于c++ - 在C++中是否有任何用于链表的内置函数,其功能类似于Java提供的indexOf函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63425357/