如何检查向量是否包含指定索引中的特定字符

How to check if a vector contains a specific character within specified indices?

本文关键字:索引 字符 包含指 是否 何检查 检查 向量      更新时间:2023-10-16

我想知道如何(如果可能的话)从向量的开头搜索到存在字符的索引。

伪代码:

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。)