如何在 c++ 中从现有 2D 向量创建具有特定列的新向量
How to create a new vector with particular columns from existing 2D vector in c++
我有 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;
}
}
相关文章:
- 计算排序向量的向量中唯一值的计数
- C++将向量的向量拆分为向量的N个子向量
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 循环向量的向量并附加到新向量
- C 矢量元素擦除与新向量创建
- 仅使用重复项创建他人的新向量
- 如何将文本文件的每一行分配给新向量
- C++数组选择平方数并创建新向量
- 如何将映射的内容从一个类复制到另一个类的新向量中
- 如何从字符串向量 c++ 而不是新向量过滤
- 在C++中检查向量项并添加到新向量中
- 将旧向量设置为等于新向量
- c ++我可以在我的代码中将这样的向量新到哈希图中吗?
- 如何使用 STL 的 copy() 从现有向量创建新向量?
- 从向量中移除元素,并将该元素添加到新向量c++中
- 如何在向量的向量开头添加新行
- 从类实例的向量中提取类成员(作为新向量)
- 将具有唯一指针的向量复制到新向量中
- c++计算一个新向量,该向量与现有向量有delta
- 如何在 c++ 中从现有 2D 向量创建具有特定列的新向量