how to get the first character or how to get a character by index from a string in a string vector while iterating through that vector. Here's my code:
vector<string>::iterator i=vec.begin();
while(i!=vec.end()){
if(i[0]==ch)
cout<<"output";
}
it's giving the error:
no match for 'operator==' (operand types are 'std::basic_string' and 'char')|
Try the following
vector<string>::iterator i=vec.begin();
while(i!=vec.end()){
if(i[0][0] == ch)
cout<<"output";
++i;
}
i[0]
returns the whole string pointed to by iterator i while i[0][0]
returns the first character of the string even if the string is empty (in this case the value will be '\0'). :)
But you could write simpler
for ( const std::string &s : vec )
{
if ( s[0] == ch ) cout << "output";
}
If you want to use some index that can have any value then the code could look like
vector<string>::iterator i=vec.begin();
while(i!=vec.end()){
if( index < i[0].size() && i[0][index] == ch)
cout<<"output";
++i;
}
Or
for ( const std::string &s : vec )
{
if ( index < s.size() && s[index] == ch ) cout << "output";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With