【发布时间】:2013-11-18 13:53:55
【问题描述】:
我的问题与How to find an item in a std::vector? 非常相似但是,我想更进一步,假设我要搜索的项目在向量中出现了几次,我也想获得它在向量中的位置。例如,我的向量是[ 1 3 4 3 7],我要搜索的项目是3。那么项目的位置是1 和3。使用std::find 函数,我只能获得它在向量中的第一个位置。有任何想法吗?
【问题讨论】:
我的问题与How to find an item in a 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);
}
【讨论】:
size_t 而不是 unsigned 来实现此目的 - 如果它们的大小不匹配(例如 64 位上的巨大向量),您的代码可能会失败系统)。
连续使用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)。
【讨论】: