如何获取字符串流中存储的字符串数量
我需要测试从 string_view
中提取的 string
数量是否等于特定数字(例如 4),然后执行一些代码。
我是这样做的:
#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';
}
}
可以看出,上述代码的缺点之一是,如果计数不等于 4,则意味着 foundTokens
的构造完全是浪费,因为它稍后将不会在代码中使用。
有没有办法检查 ss
中存储的 std::string
的数量,然后如果它等于某个数字,则构造向量?
I need to test to see if the number of extracted string
s 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::string
s stored in ss
and then if it is equal to a certain number, construct the vector?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,字符串流内部只是一个字符序列,它不知道所包含的数据可能具有什么结构。您可以首先迭代字符串流并发现该结构,但这并不比简单地提取字符串更有效。
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.
您可以执行类似以下操作
之后,比较变量 n 的值,您可以决定是否创建向量。
例如
You can do it something like the following
After that comparing the value of the variable
n
you can decide whether to create the vector or not.For example