如何检查向量是否包含指定索引中的特定字符
How to check if a vector contains a specific character within specified indices?
我想知道如何(如果可能的话)从向量的开头搜索到存在字符的索引。
伪代码:
vector<char> a{a, b, c, d, e, f, /*...*/};
if (from a.begin() to a[2] b exists) {
... }
最有效的方法是什么?
算法算法,而不是容器,因此您可以使用它们:
auto it = std::find(a.begin(), a.begin() + 2, 'b');
if (it != a.begin() + 2) {
// found.
}
带有以下定义:
vector<char> a = {'a', 'b', 'c', 'd', 'e', 'f' /*...*/};
char ch = 'x';
您可以轻松地进行以下操作,从第一个字符(+1
)开始,然后忽略两个元素(-2
):
if (any_of(a.cbegin()+1, a.cend()-2, [&ch](auto &x){return x==ch; }))
cout << "found !"<<endl;
else cout << "not found! "<<endl;
您也可以在<algorithm>
库中使用更古典的std::find()
:
if (std::find(a.cbegin(), a.cend(), ch) !=a.cend())
...
如果要在给定偏移量或端忽略某些尾随元素时开始,则可以在开始或结束迭代器上进行迭代数学:
if (std::find(a.cbegin()+3, a.cend(), ch) != a.cend())
...
如果您经常这样做,并且您在矢量中找到元素的位置不感兴趣,则可以考虑以下功能:
template <class U, class W>
bool myfind (const U &v, size_t starto, size_t endo, const W& x) {
if (starto>=endo || endo>=v.size())
return false;
return std::find(v.begin()+starto, v.begin()+endo, x) != v.begin()+endo;
}
如果您可以使用std::string
而不是std::vector
,则可以使用成员函数find()
,可以将其偏移作为参数。
#include<vector>
#include<iostream>
using namespace std;
int main(){
vector<char> A;
//initialize your vector here
unsigned i;
unsigned start, stop;
//initialize the start and stop here
for(i=start; i<stop; i++){
if(A[i]=='b'){
cout<<"character found!"<<endl;
break;
}
}
}
只要您在非级数容器上操作(std::vector
是一个),我会选择std::any_of
来表达您的意图。它的效率与std::find
#include <vector>
#include <algorithm>
int main()
{
std::vector<char> a{'a', 'b', 'c', 'd', 'e', 'f'};
// Checks range between 'b'...'d'
if (std::any_of(a.begin() + 1, a.end() - 2, [](char c){return c == 'b';})) {
// do stuff
}
return 0;
}
其他是正确的,由于算法带有迭代器,因此您在这里有足够的灵活性。
这是我的变体。
我坚持使用std::find
,因为std::any_of
添加了复杂性而不增加清晰度。
std::vector<char> a{'a', 'b', 'c', 'd', 'e', 'f', /*...*/};
assert(a.size() >= 2);
const auto start = a.cbegin();
const auto end = a.cbegin() + 2;
const char search = 'b';
if (auto it = std::find(start, end, search); it != end)
{
std::cout << "Found '" << search << "'!n";
}
(以下是新的if
结构;如果您是pre-c 17。)
相关文章:
- 将转换字符键入 int 以用作向量C++的索引
- 查找字符在两个索引之间出现的次数
- *无符号字符中的索引值
- C++ char 类查找字符索引
- int 数组,但索引是字符?
- 为什么在 c++ 中索引字符串会发出隐式转换警告?
- 根据字符获取数组的索引
- CPP:如何获取字符的最后一个索引
- 如何计算 3d 数组中的索引值在内存中的位置?如何计算字符**中的索引值在内存中的位置?
- 将特定索引处的字符数组内容与字符文字 - cpp 进行比较
- 为字符串中的每个字符(不是字符位置!)分配唯一的索引
- 通过字符串的字符对整数数组进行索引
- 从给定索引返回子字符字符串的函数
- 在C 字符串中,为什么在最后一个字符之后,通过索引和()访问索引时行为是不同的
- 是否可以使用字符串或字符索引数组
- 如何使该程序在数组中打印搜索字符的索引,否则将找不到它
- 如何在 C++ 的字符串中打印从一个索引到另一个索引的字符范围
- 为什么在使用字符索引数组时会出现这种不同的行为
- 尝试在字符串中索引字符并创建新字符串
- c++中字符串中的偶数和奇数索引字符