如何使用c ++中现有2D向量的特定列创建新向量

时间:2014-04-08 08:13:26

标签: c++ vector stdvector

我有2D矢量(vector<vector<string>>)有很多列(m * n)(这里我提到这个2D矢量作为Maintable)。我想用主表中的几个特定列创建一个新的向量。 例如,假设如果我有一个包含12列的主表,我想将主表中的任何3个非连续列转换为新的2D Vector。怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

//...

const size_t N = 10;
std::string a[] = { "A", "B", "C", "D", "E", "F" };
std::vector<std::vector<std::string>> v1( N, std::vector<std::string>( std::begin( a ), std::end( a ) ) );
std::vector<std::vector<std::string>> v2;

v2.reserve( v1.size() );

for ( const std::vector<std::string> &v : v1 )
{
    v2.push_back( std::vector<std::string>(std::next( v.begin(), 2 ), std::next( v.begin(), 5 ) ) );
}

for ( const std::vector<std::string> &v : v2 )
{
    for ( const std::string &s : v ) std::cout << s << ' ';
    std::cout << std::endl;
}

使用C ++ 2003语法重写代码很简单。例如,你可以写

std::vector<std::vector<std::string>> v1( N, 
                                          std::vector<std::string>( a, a + sizeof( a ) / sizeof( *a ) ) );

而不是

std::vector<std::vector<std::string>> v1( N, std::vector<std::string>( std::begin( a ), std::end( a ) ) );

等等。

编辑:如果列不相邻,则可以使用以下方法

#include <iostream>
#include <vector>
#include <array>
#include <string>
#include <iterator>
#include <algorithm>


int main()
{
    const size_t N = 10;
    const size_t M = 3;

    std::string a[N] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };
    std::vector<std::vector<std::string>> v1( N, std::vector<std::string>( std::begin( a ), std::end( a ) ) );
    std::vector<std::vector<std::string>> v2;

    v2.reserve( v1.size() );

    std::array<std::vector<std::string>::size_type, M> indices = { 2, 5, 6 };

    for ( const std::vector<std::string> &v : v1 )
    {
        std::vector<std::string> tmp( M );
        std::transform( indices.begin(), indices.end(), tmp.begin(),
            [&]( std::vector<std::string>::size_type i ) { return ( v[i] ); } );
        v2.push_back( tmp );
    }

    for ( const std::vector<std::string> &v : v2 )
    {
        for ( const std::string &s : v ) std::cout << s << ' ';
        std::cout << std::endl;
    }
}