如何在不使用STL的情况下,根据参数将元素添加到循环内的两个不同数组中

How do I add elements to two different arrays inside of a loop based on parameters without using the STL?

本文关键字:循环 数组 两个 添加 STL 情况下 参数 元素      更新时间:2023-10-16

我对C++很陌生,所以请告诉我是否有更简单的方法来完成我想要做的事情。

基本上,我在命令行上检查两种不同类型的输入命令。如果用户输入一个C,后面跟着一个整数(在这种情况下是1)(我不需要错误检查),那么它应该将"C1"添加到我的第一个数组中。如果他们键入A 1 2 400,那么它应该将其添加到第二个数组中。

在java中,我只需键入

if (input.contains("c")){
cityArray.add(input)
else if (input.contains ("a"){
routeArray.add(input)
    } 

或者类似的东西。

以下是我在C++中的内容

while(loopCheck == false )
  {
  cout << "Please Enter A Command:> "  << endl;
  cin >> Input;
  if((cin >> c) ){
  cout << "Citys: " << city[] << endl;
  }
  if (cin == " "){
      loopCheck = true;
  }

}

它实际上与Java没有太大区别。下面是一个使用switch语句进行输入处理的示例。您可以将其作为if子句进行练习。

#include <iostream>
int main()
{
   std::string line;
   bool stop = false;
   while (!stop && getline(std::cin, line)) {
      switch (line[0]) {
         case 'C':
            // add to first array
            std::cout << "Case 'C': '" << line << "'n";
            break;
         case 'A':
            // add to second array
            std::cout << "Case 'A': '" << line << "'n";
            break;
         default:
            stop = true;
            break;
      }
   }
}

我跳过了插入数组的部分,您应该考虑允许或应该使用什么。由于您不被允许使用STL,您应该查看您的课堂笔记和问题陈述,了解有关数组(动态和静态数组)的知识。

请记住,您不会在当今的C++应用程序中使用STL。

目前,我假设问题中的C++代码无关紧要,您主要是在寻找包含的Java代码的合理模拟。在这种情况下,看起来与Java代码相似的C++代码可能看起来像这样:

std::string input;
std::vector<std::string> cityArray;
std::vector<std::string> routeArray; 
// ...
if (input.find('c') != std::string::npos) {
    cityArray.push_back(input);
}
else if (input.find('a') != std::string::npos) {
     routeArray.push_back(input);
}

如果我个人是用C++写的,我可能会做一些更像这样的事情:

std::map<char, std::vector<std::string>> arrays;
// ...
arrays[input[0]].push_back(input);

另一种可能性(消除了使用vector)是使用std::multimap

std::multimap<char, std::string> arrays;
arrays.insert(std::make_pair(input[0], input));

至于不允许使用标准图书馆:用棍子敲你老师的头。如果不使用标准库,您就无法读取任何输入或生成任何输出(仅举几个例子),因此出于任何实际目的,您的代码都无法执行任何操作。您还可以将每个程序都编写为int main() {}并使用它,因为这基本上相当于在没有标准库的情况下可以做的任何事情。