c++ - 在C++中是否有任何用于链表的内置函数,其功能类似于Java提供的indexOf函数?

标签 c++ list linked-list

我正在使用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/

相关文章:

c# - 获取从 C# 调用的 COM 方法的错误消息

C++令人困惑的编译错误

c# - 实现自定义 Int+Range 列表解决方案

c++ - C 链表 - 不允许指向不完整类的指针

c - 尝试制作链表,出现段错误

C++ 类型特征虚拟示例 : compiler error

C++ - 具有 volatile 变量的模板函数 - 无法调用模板特化

python - 如何编写一个python函数,当输入是列表时返回列表,当输入是非列表时返回非列表值?

python - 在 python 中使用 heapq 获取优先级列表时出现问题

java - 如何递归地获取链表的大小?