I need to test to see if the number of extracted strings from a string_view is equal to a specific number (e.g. 4) and then execute some code.
This is how I do it:
#include <iostream>
#include <iomanip>
#include <utility>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include <iterator>
int main( )
{
const std::string_view sv { " a 345353d& ) " }; // a sample string literal
std::stringstream ss;
ss << sv;
std::vector< std::string > foundTokens { std::istream_iterator< std::string >( ss ),
std::istream_iterator< std::string >( ) };
if ( foundTokens.size( ) == 4 )
{
// do some stuff here
}
for ( const auto& elem : foundTokens )
{
std::cout << std::quoted( elem ) << '\n';
}
}
As can be seen, one of the downsides of the above code is that if the count is not equal to 4 then it means that the construction of foundTokens was totally wasteful because it won't be used later on in the code.
Is there a way to check the number of std::strings stored in ss and then if it is equal to a certain number, construct the vector?
NO, a stringstream internally is just a sequence of characters, it has no knowledge of what structure the contained data may have. You could iterate the stringstream first and discover that structure but that wouldn't be any more efficient than simply extracting the strings.