gpt4 book ai didi

c++ - 返回列表C++中元素的索引

转载 作者:行者123 更新时间:2023-12-02 10:04:43 25 4
gpt4 key购买 nike

看来这是一个非常常见的问题,但是它们都是在 python 中提出的。我想在列表中返回搜索元素的索引,而不是STL!

我的功能

void checkNode(LinkedList* head, int v)
{
LinkedList* p = head;
while (p != NULL) {
if (p->data == v) {
cout << ; // here should be answer i suppose
}
else {
cout << -1;
}

p = p->next;
}

}

最佳答案

您需要声明i,并在遍历列表时增加计数:

void checkNode(LinkedList* head, int v)
{
LinkedList* p = head;
int i=0; // Declare i
while (p != NULL) {
if (p->data == v) {
cout << i; // output i
return;
}
++i; // Increment index counter
p = p->next;
}
// we've searched through the entire list
cout << -1; // not found
}

万一您实际上想要返回声明的索引而不是代码建议的索引。它看起来像这样:
int checkNode(LinkedList* head, int v)
{
LinkedList* p = head;
int i=0; // Declare i
while (p != NULL) {
if (p->data == v) {
return i;
}
++i; // Increment index counter
p = p->next;
}
// we've searched through the entire list
return -1; // not found
}

关于c++ - 返回列表C++中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60855556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com