首页 > 解决方案 > c++ 中是否有任何用于链接列表的内置函数,其工作方式类似于 java 提供的 indexOf 函数?

问题描述

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

等等

标签: c++listlinked-list

解决方案


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;
}

推荐阅读