gpt4 book ai didi

c++ - vector 如何找到第一个和最后一个当前值

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:37:49 27 4
gpt4 key购买 nike

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

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;
}

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

最佳答案

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

DEMO

int main()
{
std::vector<int> v = {1,2,3,1,6,2,1};

const int currentVal = 1;
const auto itf = std::find(v.cbegin(), v.cend(), currentVal);
const auto itb = std::find(v.crbegin(), v.crend(), currentVal);

if(itf != v.cend()){
std::cout << "front pos: " << std::distance(v.cbegin(), itf) << std::endl;
std::cout << "back pos : " << (v.size() - std::distance(v.crbegin(), itb) - 1) << std::endl;
}
else{
std::cout << currentVal << " is not found." << std::endl;
}

return 0;
}

关于c++ - vector 如何找到第一个和最后一个当前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078066/

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