将字符串添加到未知大小的数组c++中
Adding String to an unknown-size array c++
我在C++中使用数组时遇到一些问题。看,我想让用户以String
的形式给程序一个输入,并一直这样做,直到用户满意为止。我的输入工作正常,但当我想将字符串存储到数组中时,我会遇到一些问题。显然,我必须为我的数组定义一个大小?有没有办法将输入存储在2或3个不同的arrays
(取决于输入,我用一些if语句对其进行排序)字符串中,然后打印出来?我的代码现在看起来像这样。。
string firstarray[10];
string secarray[10];
//The cin stuff here and reading strings from user-input
if(MyCondition1){
for(int x = 0; x<=9;x++){
firstarray[x] = name;
}
if(MyCondition2){
for(int x = 0; x<=9;x++){
secarray[x] = name;
}
有没有办法跳过数组的10限制?它会像字符串吗
firstarray[];
您正在寻找一个std::列表。或者更好的是,一个std::向量,它允许您根据元素的位置访问元素。
两者都可以动态扩展。
using namespace std;
// looks like this:
vector<string> firstvector;
firstvector.push_back(somestring); // appends somestring to the end of the vector
cout << firstvector[someindex]; // gets the string at position someindex
cout << firstvector.back(); // gets the last element
关于您的第二个问题:
当然,您可以创建几个数组/向量来放入字符串。甚至可以使用类型为map<key, vector<string>>
的std::映射,其中key
可以是类别的枚举(或字符串,但枚举更好)。
您将一个新值放入其中一个向量中:
tCategoryEnum category = eCategoryNone;
switch(condition)
{
case MyCondition1:
category = eCategory1;
break;
case MyCondition2:
category = eCategory2;
break;
// ...
}
// check if a category was found:
if(category != eCategoryNone)
{
categoryMap[category].push_back(name);
}
然后输出这个,你可以简单地循环每个类别和向量元素
for(int i = 0; i < categoryMap.size(); i++)
for(int j = 0; j < categoryMap[i].size(); j++)
cout << categoryMap[i][j];
您是否考虑过使用std::vector<string> >
?
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '