c++ - 用不同大小的元素实现一个字符串数组
问题描述
如何实现不同大小的字符串数组,即数组stringar[4]={"black","red","blue","green"}
。另外,如何访问 C++ 中每个元素的单个字母/字符?编辑:这是我在 CPP 中尝试过的。但它为所有输入提供相同的输出(即 0)。代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{ int n,i,j,p,q,f=0,count=0,key,m;
char s[100][100];
cin>>n;
for( i = 0; i < n; i++)
for (j = 0; j < 100; j++)
cin >> s[i][j];
for(i=0;i<n;i++)
{
for (j = 0; j < 100; j++)
{
key = s[i][j];
for (p = i + 1; p < n; p++)
{
for (q = 0; q < m; q++)
{
if (key == s[p][q]) {f = 1;break;}
else {f = 0;continue;}
}
}
if (f == 1)
count++;
}
}
cout<<count;
return 0;
}
解决方案
最后,您需要将其想象为具有可变大小的矩阵。
[b][l][a][c][k]
[r][e][d]
[b][l][u][e]
[g][r][e][n]
std::vector<std::string> stringar;
stringar.push_back( "black" );
stringar.push_back( "red" );
char letter = stringar[ 0 ][ 1 ];
char letter2 = stringar[ 1 ][ 2 ];
letter
将在位置 0 的矩阵中的数组的位置 1 中具有字母:
位置 0 中的数组:black
。位置 1 中的字母:l
位置 1 中的数组:red
. 位置 2 中的字母:d
[b][l][a][c][k]
[r][e][d]
编辑:
正如您在评论中问我的那样,这是一个粗略的实现,因此您可以看到它是如何完成的!(请原谅我printf
,cout
但我无法使用它。
int rows = 4; //black, red, blue, green ==> 4 elements
int cols[4] = { 5, 3, 4, 5 }; // 5 letters for black, 3 letters for red, etc.
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols[i]];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols[i];j++) {
matrix[i][j] = 0;
printf("%d", matrix[i][j]);
}
printf("\n");
}
这将显示此输出,这就是您要查找的内容(而不是0
s,您需要的任何矿物质)。
00000 (black)
000 (red)
0000 (blue)
00000 (green)
推荐阅读
- keras - 使用共享层保存 keras 模型
- php - 如何使用 curl 在谷歌事件日历 API 中添加附件?
- download - telegram android 使用什么类型的库来下载和上传文件?
- mobile - 滚动时如何隐藏 BottomNavigationBar - Flutter
- devexpress - devexpress RepositoryItemRadioGroup 项目文本被剪裁
- firebase - 反应本机警报功能
- ios - Xcode 9:在 Xcode 9 上运行时,向表格视图单元格添加了奇怪的侧边填充
- postgresql - 如何在querydsl中减去小时数?
- java - 如何反序列化 JSON 数组以列出?
- vhdl - 在数组中查找最小值的问题