/ / c ++で既存の2Dベクトルから特定の列を持つ新しいベクトルを作成する方法 - c ++、vector、stdvector

c ++で既存の2Dベクトルから特定の列を持つ新しいベクトルを作成する方法 - c ++、vector、stdvector

私は2D Vectorを持っています(vector<vector<string>>(m * n)列が多い(ここで私は述べたメインテーブルとしてこの2次元ベクトル)。メインテーブルからいくつかの特定の列を持つ新しいベクトルを作成したいです。 たとえば、12列のメインテーブルがある場合、メインテーブルから3つの不連続列を新しい2D Vectorに取り込むとします。どうやってするか?

回答:

回答№1は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;
}
}