将字符串添加到未知大小的数组c++中

Adding String to an unknown-size array c++

本文关键字:数组 c++ 字符串 添加 未知      更新时间:2023-10-16

我在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> >