Кажется, вы имеете в виду следующее
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<std::string> v = { "a", " ", "", "b", "c", " ", "d" };
auto is_empty = []( const std::string &s )
{
return s.find_first_not_of( " \t" ) == std::string::npos;
};
v.erase( std::remove_if( std::begin( v ), std::end( v ), is_empty ), std::end( v ) );
for ( const auto &s : v )
{
std::cout << "\"" << s << "\" ";
}
std::cout << std::endl;
return 0;
}
Вывод программы:
"a" "b" "c" "d"
Что касается вашего кода, то он неэффективен, потому что вы пытаетесь удалить каждый найденный элемент отдельно и это l oop, например
for (auto it = s1.begin(); it != s1.end() && isspace(*it); )
{
it = s1.erase(it);
}
не может повторяться никогда, потому что первый элемент не удовлетворяет условию isspace(*it)
, которое, кроме того, недопустимо. То есть вы передаете объект типа std::string
функции, которая ожидает объект типа char
(точнее, типа int
).
Если использовать C функции isspace
, тогда программа может выглядеть следующим образом.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
#include <cctype>
int main()
{
std::vector<std::string> v = { "a", " ", "", "b", "c", " ", "d" };
auto is_empty = []( const std::string &s )
{
return std::all_of( std::begin( s ), std::end( s ),
[]( char c )
{
return std::isspace( ( unsigned char )c );
} );
};
v.erase( std::remove_if( std::begin( v ), std::end( v ), is_empty ), std::end( v ) );
for ( const auto &s : v )
{
std::cout << "\"" << s << "\" ";
}
std::cout << std::endl;
return 0;
}
Вывод программы такой же, как показано выше.