如何在 c++ 中从现有 2D 向量创建具有特定列的新向量

How to create a new vector with particular columns from existing 2D vector in c++

本文关键字:向量 新向量 创建 c++ 2D      更新时间:2023-10-16

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

你可以按如下方式使用一些东西

#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;
    }
}