将一个数组的每个元素拆分为另一个数组

Splitting each element of an array into an another array

本文关键字:数组 元素 拆分 另一个 一个      更新时间:2024-09-21

我目前正在处理一个C++项目。对于这个项目,我需要将一个数组的元素拆分为另一个数组。我会详细说明我的需要。目前,我有一个这样的数组:

array_1 = [first,second,third]

我需要把这个数组改成这样:

array_2 = [[f,i,r,s,t],[s,e,c,o,n,d],[t,h,i,r,d]]

我该怎么做?这对我将是一个很大的帮助。谢谢你阅读我的问题。

C++为这个问题提供了大量的解决方案。一种方便的方法是使用CCD_ 1。请参见以下内容。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> array_1 = {"first","second","third"};
vector< vector<char> > array_2;

for(int i(0); i < array_1.size(); ++i){
vector<char> charVec(array_1[i].begin(), array_1[i].end()); 
array_2.push_back( charVec );
}

return 0;
}

您可以使用std矢量库来实现这一点。在这个例子中,我使用了字符串和字符,但对于其他类型应该是一样的(std矢量库使用模板(。

#include <stdio.h>
#include <string>
#include <vector>
int main ()
{
//We initialize our vectors
std::vector<std::string> array1;
array1.push_back("first");
array1.push_back("second");
array1.push_back("third");
std::vector<char> array2;
//Now, using the string's fuction .size() we can iterate our string and save
//each character into array2 with push_back()
for(int i=0; i<array1.size(); i++)
{
std::string aux = array1[i];
for(int j=0; j<aux.size(); j++)
{
array2.push_back(aux[j]);
}
}
//Finally we print the result
for(int i=0; i<array1.size(); i++)
{
printf("%sn",array1[i].c_str());
}
for(int i=0; i<array2.size(); i++)
{
printf("%cn",array2[i]);
}
return 0;    
}

您的array_1中似乎没有类型,所以我假设它是std::vector<std::string>

std::vector<std::string> array_1 = {"first", "second", "third"};

并且假设array_2是字符向量的向量:std::vector<std::vector<char>>

您需要在array_1上循环,然后在每个字符串中的每个字符上循环。创建一个新矢量并将其放入array_2

for(const auto& word : array_1)
{
std::vector<char> vec;
for(const auto& c : word)
{
vec.push_back(c);
}
array_2.push_back(vec);
}

完整的工作实施将是:

#include <vector>
#include <string>
int main()
{
std::vector<std::string> array_1 = {"first", "second", "third"};
std::vector<std::vector<char>> array_2 = {};
for(const auto& word : array_1)
{
std::vector<char> vec;
for(const auto& c : word)
{
vec.push_back(c);
}
array_2.push_back(vec);
}
}