向量如何找到第一个和最后一个当前值

时间:2019-03-09 13:55:26

标签: c++ algorithm vector find

任务:查找第一个和最后一个当前值。 示例:

vector = {1,2,3,1,6,2,1};

need value 1 =>

 first index = 0, last = 6; (index/position);



    vector<int>::iterator it = find(v.begin(), v.end(), 1); 
    if (it != v.end())
    {
        cout << "Element Found" << std::endl;

        // Get index of element from iterator
        int index =      distance(v.begin(), it);
        int lastindex  = distance(v.end(), it); // bad try to find
        cout <<"Index of first element in vector : "<<index<<" last elem ";
// bad code <<lastindex - index <<endl;
    }
    else
    {
        cout << "Element Not Found" << std::endl;
    }

我找到了第一个位置,但是找不到最后一个位置。 需要帮助)

2 个答案:

答案 0 :(得分:1)

您可以使用反向迭代器如下查找最后一个元素:

DEMO

int

答案 1 :(得分:-1)

您可以使用“ rbegin”和“ rend”来反转列表,并使用与现在相同的代码来查找最后一个出现的事件。

vector = {1,2,3,1,6,2,1};

need value 1 =>

 first index = 0, last = 6; (index/position);



    vector<int>::iterator it = find(v.begin(), v.end(), 1); 
    vector<int>::iterator it_reverse = find(v.rbegin(), v.rend(),1);
    if (it != v.end() && it_reverse != v.rend())
    {
        cout << "Element Found" << std::endl;

        // Get index of element from iterator
        int index =      distance(v.begin(), it);
        int lastindex  = distance(v.rend(), it_reverse); // bad try to find
        cout <<"Index of first element in vector : "<<index<<" last elem ";
    }
    else
    {
        cout << "Element Not Found" << std::endl;
    }
相关问题