c++ - 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
等等
解决方案
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;
}
推荐阅读
- java - 为什么我的代码会导致编译器错误?
- angular - 如何在离子警报无线电警报中获得选定的值
- laravel - 未找到 Laravel 5.8 Passport 404
- angular - 如何以编程方式设置 owl 日期时间选择器格式?
- .net-core - yum-cron 过于激进地更新 dotnet SDK
- python - 如何引用项目目录中的文件?
- jquery - WP Contact Form 7:防止在按回车键时提交表格
- dart - 好或坏:在 Dart/Flutter 中声明主方法异步
- java - How to check if a word can be composed of entries in an array?
- javascript - 在较小的屏幕上,滑出选项卡应该粘在 Div 的左侧,无论如何