如何在 std::vector 中查找项目的位置
How to find the positions of an item in a std::vector
我的问题与如何在 std::vector 中查找项目非常相似?但是,我想更进一步,假设我正在搜索的项目在向量中出现多次,并且我也想获得它在向量中的位置。例如,我拥有的向量是[ 1 3 4 3 7]
,而我要搜索的项目是3
。然后项目的位置是1
和3
。使用 std::find
函数,我只能获得它在向量中的第一个位置。有什么想法吗?
只需将其粘贴在 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);
}
连续使用std::find
次,然后将所有结果放在一起。用作您找到的范围first
,前一个std::find
返回给您的位置加一。
您可以多次使用 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
)。
相关文章:
- 查找项目在哈希表中的位置
- 如何在Cmake中正确查找头路径,以便在我的项目中构建Box2D
- Visual Studio 2015资源视图和资源编译器使用不同的方法在项目目录中查找图标文件.如何修复
- 在5d映射C++中查找项目
- 通过查找一对项目的代码获取错误的输出,在给定的总和相等的给定列表中列表
- 查找两个 3 位数字的乘积(欧拉项目 #4)
- 更改 std::set 以按 T 类型查找项目
- C 使用字符串项目在列表中查找结构
- unordered_map仅查找先前找到的项目之后的项目
- 使用STD ::查找从向量中选择项目
- STD :: MAP-如何查找或添加,然后可以在一次搜索中删除项目
- 从项目名称查找 API 中查找项目
- 在给定键 (C++) 的地图向量内查找项目
- 如何在助推向量中查找项目
- 如何在 std::vector 中查找项目的位置
- 根据世界位置查找一维数组中的通用项目
- 如何在场景中查找项目
- 如何检查/查找项目是否在DEQUE中
- 在矢量中查找项目
- 如何在ublas::矩阵中查找项目的所有出现项