将一个数组的每个元素拆分为另一个数组
Splitting each element of an array into an another array
我目前正在处理一个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);
}
}
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 尝试递归获取数组元素的总和
- 使用SWIG将numpy数组元素(int)传递给c++int