简体   繁体   English

在 boost 中,如何将 boost 迭代器传递给 function 以某种方式转换为 std::string

[英]In boost, how to pass boost iterator to a function somehow casted as std::string

See specific question as a comment at the end of the following code.请参阅以下代码末尾的特定问题作为注释。

std::string s("my sample string \"with quotes\"");

boost::escaped_list_separator<char> 
els(""," ","\"\'");

boost::tokenizer<boost::escaped_list_separator<char> >::iterator 
itr;

boost::tokenizer<boost::escaped_list_separator<char> > 
tok(s, els);

itr=tok.begin();
if (itr!=tok.end()) 
    fn_that_receives_pointer_to_std_string(itr); // <---- IS IT POSSIBLE TO SEND POINTER AND NOT HAVE TO CREATE A NEW STRING ??

boost::tokenizer<boost::escaped_list_separator<char> >::iterator is not a pointer to std::string , but you can turn it into std::string const * with boost::tokenizer<boost::escaped_list_separator<char> >::iterator不是指向std::string的指针,但是您可以将其转换为std::string const * with

&(*itr)

If a const pointer is not what you must pass, you may be able to do如果const指针不是你必须传递的,你可以做

std::string s(*itr);

and pass &s , depending on the ownership semantics of fn_that_receives_pointer_to_std_string .并传递&s ,具体取决于fn_that_receives_pointer_to_std_string的所有权语义。 Boost Tokenizer does no distinguish between iterator and const_iterator , so the result of operator* is always const . Boost Tokenizer不区分iteratorconst_iterator ,所以operator*的结果总是const

*itr will actually return a basic_string instead of a string , so you need to convert one to another: *itr实际上会返回basic_string而不是string ,因此您需要将一个转换为另一个:

using namespace std;
using namespace boost;

void fn_that_receives_pointer_to_std_string(string* str)
{
    cout << "str: " << *str << endl;
}

int main()
{
   string s = "Field 1,\"putting quotes around fields, allows commas\",Field 3";
   tokenizer<escaped_list_separator<char> > tok(s);
   for(tokenizer<escaped_list_separator<char> >::iterator beg=tok.begin(); beg!=tok.end();++beg)
   {   
       string tmp(*beg);
       fn_that_receives_pointer_to_std_string(&tmp);
   }   
}

I don't like the idea to passing the memory address of a string to another function.我不喜欢将string的 memory 地址传递给另一个 function 的想法。 Consider passing it by copy or by reference.考虑通过副本或引用传递它。

Sorry, it's impossible.对不起,这是不可能的。

It's exactly the reason why the rule "take string parameters as std::string " is wrong.这正是“将字符串参数作为std::string规则错误的原因。 boost::iterator_range<const char*> can be better when a template is inappropriate (separate compilation for example). boost::iterator_range<const char*>当模板不合适时会更好(例如单独编译)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM