【问题标题】:How to find the positions of an item in a std::vector如何在 std::vector 中查找项目的位置
【发布时间】:2013-11-18 13:53:55
【问题描述】:

我的问题与How to find an item in a std::vector? 非常相似但是,我想更进一步,假设我要搜索的项目在向量中出现了几次,我也想获得它在向量中的位置。例如,我的向量是[ 1 3 4 3 7],我要搜索的项目是3。那么项目的位置是13。使用std::find 函数,我只能获得它在向量中的第一个位置。有任何想法吗?

【问题讨论】:

    标签: c++ std stdvector


    【解决方案1】:

    只要把它放在一个while循环中,

        auto i = std::find(v.begin(), v.end(), n);
        std::vector<std::size_t> result;
        while(i != v.end())
        {
          result.push_back(std::distance(v.begin(), i));
          i = std::find(i + 1, v.end(), n);
        }
    

    【讨论】:

    • +1,但您应该使用 size_t 而不是 unsigned 来实现此目的 - 如果它们的大小不匹配(例如 64 位上的巨大向量),您的代码可能会失败系统)。
    【解决方案2】:

    连续使用std::find,然后将所有结果放在一起。用作你找到的范围的first,前一个std::find返回给你的位置加一。

    【讨论】:

    • @MatteoItalia 非常感谢。我修正了我的答案。
    【解决方案3】:

    您可以多次使用std::find

    std::vector<int> vec;
    // fill the vector with numbers
    std::vector<int>::iterator it = vec.begin();
    while (it != vec.end())
    {
        it = std::find(it, vec.end(), 3);
        // do something with *it
        if (it != vec.end())
            it++;
    }
    

    或者你可以简单地使用std::for_each:

    std::vector<int> vec;
    // fill the vector with numbers
    std::for_each(vec.begin(), vec.end(), [&](int i)
    {
        if (i == 3)
        {
            // do something
        }
    });
    

    如果您正在寻找项目的索引/迭代器,您可以简单地使用自定义循环:

    std::vector<int> vec;
    // fill the vector with numbers
    std::vector<int> results;
    for (std::size_t i = 0; i < vec.size(); ++i)
    {
        if (vec[i] == 3)
        {
            results.push_back(i);
        }
    }
    

    results 将保存与您的条件匹配的元素的所有索引(在本例中为==3)。

    【讨论】:

    • 感谢 cmets,但如果我使用 std::for_each 方法,我认为我无法获得项目的位置。 if (i==3) { //do something} 我怎样才能得到项目的位置?
    • @feelfree 您是要获取它的索引还是迭代器?
    • 我正在寻找它的索引。
    • @feelfree 已更新以包含该选项。
    猜你喜欢
    • 2010-11-28
    • 1970-01-01
    • 2013-03-08
    • 2016-01-07
    • 2018-01-11
    • 2010-10-08
    • 1970-01-01
    • 2012-10-03
    • 2017-12-15
    相关资源
    最近更新 更多