如何在给定的起始位置之前找到容器中的元素
How to find an element in a container before a given starting position?
我想找到容器中某个给定起始位置之前元素最后一次出现的。
例如,如果我试图在字符串的s中找到给定字符之前的最后一个空格,我相信显而易见的方法是:
string::const_iterator b;
b = i; // <-- 'i' specifies where to start looking
while ((b != s.begin()) && (b[-1] != ' '))
b--;
使用STL算法有更好的方法吗?
我试过:
b = find(string::const_reverse_iterator(i),
string::const_reverse_iterator(s.begin()), " ").base();
但我不确定这是否如预期的那样有效。
您可以使用std::string::find_last_of
并指定它应该搜索的位置。下面将找到单词测试前第一个空格的位置。
#include <iostream>
#include <string>
int main()
{
std::string foo = "this is a test string";
auto pos = foo.find_last_of(" ", foo.find("test", 0));
std::cout << pos;
std::cin.get();
return 0;
}
输出:
9
出于通用目的,我认为我会使用std::find_end和一个适当的lambda函数。页面上的示例很好地说明了函数的行为。
反向迭代器解决方案将起作用:
#include <iostream>
#include <algorithm>
int main()
{
using std::string;
using const_iterator = string::const_iterator;
using const_reverse_iterator = string::const_reverse_iterator;
string s("This is an sample");
const_iterator pos = s.begin() + s.find("sample");
const_reverse_iterator result = std::find(const_reverse_iterator(pos), s.crend(), 's');
std::cout << string(s.cbegin(), result.base()) << 'n';
}
不过,您可能更喜欢@NathanOliver的解决方案。
相关文章:
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 求最大元素位置的分治算法
- 如何将元素添加到向量的字符串位置
- 这个返回元素位置的基于循环的函数有什么问题?
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 数组中所有元素的最新最小元素的第五个位置
- 是否有任何优雅的方式来遍历元素位置可以更改的列表?
- 如何从几乎排序的链表中分离放错位置的元素?
- 如何获得相同数量的第一个和第二个元素以及它们在c++中各自的位置
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 这是查找向量中元素位置的合法方法吗?
- 用于在字符串(C )向量中找到元素位置的函数中的错误
- 如何比较和存储 2 个向量的数据元素位置
- 获取与特定模式距离最小的矢量的元素位置
- 最大 N 个等元素位置的 C++ 向量
- OpenCV 从矩阵中获取条件基最大元素位置
- 有没有一种方法可以从传递给排序的lambda中获取元素位置
- 标准::多集,跟踪插入的元素位置
- 在C++中指定数组声明中的元素位置
- 获取std::vector中的元素位置