迭代到 std::vector<string>

Iteration into std::vector<string>

本文关键字:string gt lt vector std 迭代      更新时间:2023-10-16

我有一个字符串参数的vector。。。

|name1|value1|name2|value2|...

我想迭代并将名称缓存到一个字符串中,然后将其添加到名称的vector中,并用value做同样的事情。它们在std::vector<string>中。

我做:

std::vector<string> names;
std::vector<string> values;
std::vector<string>::iterator pit = p.begin();
while(pit != p.end()){
   string name = *pit;
   pit++;
   string value = *pit;
   pit++;
   names.push_back(name);
   values.push_back(value);
}

但它在vector中返回一个访问冲突。它正在访问一个返回<BadPtr>的坏位置。如何进行此迭代?它有一种为每个人使用的方法吗?

看看这个:

std::vector<string> names;
std::vector<string> values;
std::vector<string>::iterator pit = p.begin();
while(pit != p.end()){
   string name = *pit;
   pit++;
   if(pit == p.end())
   break;
   string value = *pit;
   pit++;
   names.push_back(name);
   values.push_back(name);
}

正如我在评论中所说,问题可能是,在第二次增加pit之后,您没有进行任何检查。

这里有一个演示程序,展示了如何使用标准算法std::partition_copy 来完成它

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
    std::vector<std::string> p = { "name1", "value1", "name2", "value2" };
    std::vector<std::string> names;
    std::vector<std::string> values;
    names.reserve( ( p.size() + 1 ) / 2 );
    values.reserve( p.size() / 2 );
    unsigned int i = 0;
    std::partition_copy( p.begin(), p.end(),
                         std::back_inserter( names ),
                         std::back_inserter( values ),
                         [&]( const std::string & ) { return i ^= 1; } );
    for ( const auto &s : p ) std::cout << s << ' ';
    std::cout << std::endl;
    for ( const auto &s : names ) std::cout << s << ' ';
    std::cout << std::endl;
    for ( const auto &s : values ) std::cout << s << ' ';
    std::cout << std::endl;
    return 0;
}

程序输出为

name1 value1 name2 value2 
name1 name2 
value1 value2 

同样可以使用基于范围的语句

#include <iostream>
#include <vector>
#include <string>
int main()
{
    std::vector<std::string> p = { "name1", "value1", "name2", "value2" };
    std::vector<std::string> names;
    std::vector<std::string> values;
    names.reserve( ( p.size() + 1 ) / 2 );
    values.reserve( p.size() / 2 );
    unsigned int i = 0;
    for ( const std::string &s : p )
    {
        if ( i ^= 1 ) names.push_back( s );
        else values.push_back( s );
    }
    for ( const auto &s : p ) std::cout << s << ' ';
    std::cout << std::endl;
    for ( const auto &s : names ) std::cout << s << ' ';
    std::cout << std::endl;
    for ( const auto &s : values ) std::cout << s << ' ';
    std::cout << std::endl;
    return 0;
}

因此,你的循环可以看起来更简单像

    unsigned int i = 0;
    for ( const std::string &s : p )
    {
        if ( i ^= 1 ) names.push_back( s );
        else values.push_back( s );
    }

正如您所看到的,如果使用您的方法,循环的主体仅由两个语句组成,而不是六个或八个语句。