-3

I'm trying to see if an array contains a given letter. If the array doesn't have the letter, then we add it to the array. I know how to do this in python with the not in arr syntax, but having a lot of trouble with the c++ method.

This is the python code:

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

This is my C++ code attempt:

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]);
    }
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
handavidbang
  • 593
  • 1
  • 6
  • 19
  • `vector` is an array of char, not char* or string. When you ask, please specify what's wrong with your current code, or refer to [ask]. – YiFei Apr 23 '18 at 03:17
  • 2
    Possible duplicate of [How to find out if an item is present in a std::vector?](https://stackoverflow.com/questions/571394/how-to-find-out-if-an-item-is-present-in-a-stdvector). I'm not sure I understand your exact use case ... but something like this might work for you: `std::find(vector.begin(), vector.end(), item) != vector.end()` – paulsm4 Apr 23 '18 at 03:19
  • 1
    Even if you get this code to work, this is highly inefficient if your array is already has many characters, and you want to add a unique one. Consider a helper `std::unordered_set` to test if the character is already in the vector. – PaulMcKenzie Apr 23 '18 at 03:22

1 Answers1

1

If you want just method that calcs is symbol in string or array then here are some code:

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;
        }
    }

}

Output is:

1 element contains
1 element contains
Program ended with exit code: 0
Alexey Usachov
  • 1,364
  • 2
  • 8
  • 15