如何在c中实现“不在数组中”++

2024-04-20 09:50:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想看看数组是否包含给定的字母。如果数组中没有字母,则将其添加到数组中。我知道如何在python中使用not in arr语法来实现这一点,但是在c++方法中遇到了很多麻烦。你知道吗

这是python代码:

vowel_arr = []
#Checks
for i in arr:
    if len(i)>input_pos and i[input_pos] not in vowel_arr:
        vowel_arr.append(i[input_pos])

这是我的C++代码尝试:

word_arr = [ 'c', 'co', 'cmo', 'cmop','cmopu','cmoptu', 'cemoptu', 'cemoprtu']

input_pos = 2

vowel_arr = [o,m,e]

//Creates a list that contains unique letters for a given position 
    vector <char> unique_arr;
    for(int j = 0; j < word_arr.size(); j++){
        if ((word_arr[j].size() > input_pos) && (find(unique_arr.begin(), 
unique_arr.end(), word_arr[j][input_pos]) == unique_arr.end())){
            unique_arr.push_back(word_arr[j][input_pos]);
    }
}

Tags: 代码inposforinputsizeif字母
1条回答
网友
1楼 · 发布于 2024-04-20 09:50:28

如果您只希望方法calcs是字符串或数组中的符号,那么下面是一些代码:

bool IsInString( const std::string& str, char symb )
{
    return str.find(symb) != std::string::npos;
}

int main()
{
    std::vector<std::string> VectStr {"test","qwe", "Array"};

    //Example for IsInString function
    for ( size_t i = 0; i < VectStr.size(); i++ )
    {
        if ( IsInString(VectStr[i], 'w') )
        {
            std::cout << i << " element contains" << std::endl;
        }
    }

    //Example for all containers with char 
    for ( size_t i = 0; i < VectStr.size(); i++ )
    {
        if ( std::find(VectStr[i].begin(), VectStr[i].end(), 'w') != VectStr[i].end() )
        {
            std::cout << i << " element contains" << std::endl;
        }
    }

}

输出为:

1 element contains
1 element contains
Program ended with exit code: 0

相关问题 更多 >