hel*_*lix 4 c++ string stl vector c++11
如何获取第一个字符或如何通过索引从字符串向量中的字符串获取字符,同时迭代该向量.这是我的代码:
vector<string>::iterator i=vec.begin();
while(i!=vec.end()){
if(i[0]==ch)
cout<<"output";
}
Run Code Online (Sandbox Code Playgroud)
它给出了错误:
不匹配'operator =='(操作数类型是'std :: basic_string'和'char')|
请尝试以下方法
vector<string>::iterator i=vec.begin();
while(i!=vec.end()){
if(i[0][0] == ch)
cout<<"output";
++i;
}
Run Code Online (Sandbox Code Playgroud)
i[0]
返回iterator i指向的整个字符串,同时i[0][0]
返回字符串的第一个字符,即使字符串为空(在这种情况下,值将为'\ 0').:)
但你可以写得更简单
for ( const std::string &s : vec )
{
if ( s[0] == ch ) cout << "output";
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用一些可以有任何值的索引,那么代码可能看起来像
vector<string>::iterator i=vec.begin();
while(i!=vec.end()){
if( index < i[0].size() && i[0][index] == ch)
cout<<"output";
++i;
}
Run Code Online (Sandbox Code Playgroud)
要么
for ( const std::string &s : vec )
{
if ( index < s.size() && s[index] == ch ) cout << "output";
}
Run Code Online (Sandbox Code Playgroud)