如何在不使用STL的情况下,根据参数将元素添加到循环内的两个不同数组中
How do I add elements to two different arrays inside of a loop based on parameters without using the STL?
我对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() {}
并使用它,因为这基本上相当于在没有标准库的情况下可以做的任何事情。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 使用for循环检查数组中的重复项
- 并行用于C++17中数组索引范围内的循环
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 程序在遍历所有值之前离开循环. 数组的
- 在C++中循环数组时访问结构属性
- 如何创建循环数组
- 查找 for 循环数组C++中存在最大值和最小值的值
- 有没有办法在 c++ 中创建循环数组
- OpenMP-每个线程的循环/数组界限
- 循环数组 - 从最后一个跳到第一个,反之亦然
- 循环数组时显示'stack smashing detected abc2 terminated Aborted'
- 使用循环数组实现矢量
- 为什么在循环数组时会得到奇怪的整数
- 循环数组-超出值
- 用于循环数组赋值的C++.正在返回垃圾邮件
- 在RapidJson中循环数组并获取对象元素
- 对于循环数组迭代,if循环测试索引是否为真/假,计算结果不正确
- c++循环/数组
- 有没有一种方法可以简化这个c++整数循环数组?