如何检查C++特定索引处的特定值列表

发布于 2025-02-11 20:12:23 字数 316 浏览 2 评论 0 原文

然后,我有一个列表

list<int>generic_list;

,然后将一个随机数附加到列表中

rand_num = rand();
generic_list.push_front(rand_num);

,然后检查列表是否有一个值,

find(generic_list.begin(), generic_list.end(), "generic string");

一旦我证明它在列表中,我如何找到它的特定索引?

I have a list

list<int>generic_list;

I then append a random number to the list

rand_num = rand();
generic_list.push_front(rand_num);

I then check the list for if it has a value in it

find(generic_list.begin(), generic_list.end(), "generic string");

Once I have proven that it is in the list how do I find the specific index it's at?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一抹微笑 2025-02-18 20:12:23

您可以使用 std :: distance 来解决此问题。这将从列表的开头返回“啤酒花”的数量到找到的项目。

正如您可以在 end()如果找不到任何东西)。

然后,您可以简单地 std :: distance 显示获取索引。

请参阅下面的示例代码:

#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>

int main() {
    // Define a list and populate it with some numbers
    std::list<int> myList{0,1,2,3,4,5,6,7,8,9,10};

    // Look for a value in the list
    std::list<int>::iterator result = std::find(myList.begin(), myList.end(), 7);

    // And, if found, calculate the index and show it on the display
    if (result != myList.end())
        std::cout << "Index: " << std::distance(myList.begin(), result) << '\n';
}

You can solve this problem with std::distance. This will return the number of "hops" from the begin of your list to the found item.

As you can read in the desciption of the std::find function, this will return an iterator to the found element. (end() if nothing could be found).

Then you can simply std::distance to show get the index.

Please see the example code below:

#include <iostream>
#include <list>
#include <iterator>
#include <algorithm>

int main() {
    // Define a list and populate it with some numbers
    std::list<int> myList{0,1,2,3,4,5,6,7,8,9,10};

    // Look for a value in the list
    std::list<int>::iterator result = std::find(myList.begin(), myList.end(), 7);

    // And, if found, calculate the index and show it on the display
    if (result != myList.end())
        std::cout << "Index: " << std::distance(myList.begin(), result) << '\n';
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文