【问题标题】:How to create a new vector with particular columns from existing 2D vector in c++如何在 C++ 中从现有 2D 向量中创建具有特定列的新向量
【发布时间】:2014-04-08 08:13:26
【问题描述】:

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

【问题讨论】:

  • 请分享定义,我不确定你的那些在你的std::vector中是如何表示的(因为是std::vector,是吗?)跨度>
  • 什么是二维向量?!
  • 如果您可以选择,使用std::slicestd::valarray 这样的操作会容易得多。如果不是,请考虑将您的数据设为单个 std::vector<string>,然后您可以简单地使用一些简单的索引数学将其呈现为 2D 矩阵。

标签: c++ vector stdvector


【解决方案1】:

你可以使用如下的东西

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

【讨论】:

  • 补充一下,这个语法是C++11
  • 感谢您的回复。该程序即将获取列序列。我的任务是获取不连续的列。从10列向量表中,我想取第2、5、6列。
猜你喜欢
  • 2021-01-05
  • 2013-03-14
  • 2012-07-28
  • 2021-07-26
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多