std::string and move_iterator

std::string and move_iterator

本文关键字:iterator move and string std      更新时间:2023-10-16

我正在编写一个标记化器,它将拆分一个string并将每个字段放入一个vector中。我的想法是反复使用string::find。我没有使用临时的string对象,而是使用了move_iterators,因为我认为在算法处理原始字符串时,它的字符会被窃取。但这并没有发生。

这是一个示例代码,演示了我所说的内容:

#include <vector>
#include <string>
#include <iostream>
using namespace std;
void
print_strings
    ( const vector<string> & v )
{
    unsigned int i = 1;
    for ( const auto & s : v )
        cout << "#" << i++ << "t: "" << s << """ << endl;
    return;
}
int
main
    ( void )
{
    string base( "hello, this is an example string, I like icescreams" );
    /* Vector to populate with strings */
    vector<string> v;
    /* 1: a copy of 'base' */
    v.emplace_back( base );
    /* 2: a copy of 'base' using iterators */
    v.emplace_back( base.begin() , base.end() );
    /* 3: a string that I think _should_ move from 'base' */
    v.emplace_back( make_move_iterator(base.begin()) , make_move_iterator(base.end()) );
    /* Print the strings twice so that we
     * can see if something has changed. */
    print_strings( v );
    print_strings( v );
    return 0;
}

使用g++ -std=c++11 -Wall -Wextra -Werror -O2编译时,它不会显示任何警告。

我的猜测是,string的构造函数,在其范围版本中,总是从指定范围复制。由于我不确定,我想确定,当然,看看你用过什么变通办法。

谨致问候,Kalrish

Iterator对容器一无所知。

move_iterator不能神奇地从字符串中移动。它不能只从其底层元素(即单个char)中移动,从char中移动与复制它相同。您需要使用std::move(base)

#include <vector>
#include <string>
#include <iostream>
using namespace std;
void
print_strings
    ( const vector<string> & v )
{
    unsigned int i = 1;
    for ( const auto & s : v )
        cout << "#" << i++ << "t: "" << s << """ << endl;
    return;
}
int
main
    ( void )
{
    string base( "hello, this is an example string, I like icescreams" );
    /* Vector to populate with strings */
    vector<string> v;
    /* 1: a copy of 'base' */
    v.emplace_back( base );
    /* 2: a copy of 'base' using iterators */
    v.emplace_back( base.begin() , base.end() );
    /* 3: a string that I think _should_ move from 'base' */
    std::cout << base << 'n'; // base is still untouched here
    v.emplace_back( std::move(base) ); // now it'll be moved from
    print_strings( v );
    std::cout << "base: " << base << "/basen"; // base is empty
    return 0;
}

在这里直播吧。