【发布时间】:2022-01-28 03:28:15
【问题描述】:
我有以下程序,它采用数组形式,例如:[12,34,55,6] 我正在使用 for 和 while 循环逐个字符读取,如果读取了一个数字,它将存储在向量 SumVec 中,即我面临的问题是向量一次只存储一个数字有什么办法可以解决这个问题。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
}
vector <int> SumVec;
string Nums;
int ReadNums(__int32* Array);
__int32 ArraySize;
};
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
int Solution::ReadNums(__int32* Array){
ArraySize = 0;
Array = new int[ArraySize];
for (int i = 0; i < Nums.size(); ++i) {
if (Nums[i] == '[' || Nums[i] == ']'|| Nums[i] == ',' || Nums[i] == ' '); //do nothing
else {
int j = i;
while (1) {
++j;
if (Nums[j] != '[' && Nums[j] != ']' && Nums[j] != ',') {
SumVec.push_back(Nums[j]);
}
else
SumVec.push_back(Nums[i]);
}
}
}
return ArraySize;
}
int main()
{
std::cout << "Welcome to the Two Sum!\n";
Solution Soln;
cout << "nums = "; //[12,34,55,6]
cin>>Soln.Nums ;
__int32* ArrayRequst = new __int32[Soln.ArraySize];
Soln.ReadNums(ArrayRequst);
for (auto i = Soln.SumVec.begin();i!= Soln.SumVec.end(); ++i){
cout << *i << endl;
}
}
当前输入:[12,34,55,6]
当前输出:
1
2
3
4
5
5
6
【问题讨论】:
-
您需要从子字符串中解析数字,您的代码只检查单个字符
-
不要使用所谓的“竞赛”或“在线评委”网站来学习编程。您在代码中犯了几个初学者错误,通过阅读some good books 并参加课程以正确学习,可以轻松避免这些错误。
-
@Omar 那么他们给了你不好的建议!显示的代码中存在太多问题,并不是一两件简单的事情会“神奇地”解决问题。很抱歉,您对 C++ 的了解是主要问题之一。 C++ 不能靠猜来教,你真的需要从基本的“hello world”程序开始学习,并一步一步地正确学习。
-
@Someprogrammerdude cout
-
代码中的几个问题:
Array是做什么用的?为什么不释放ReadNums中分配的内存?为什么允许用户未经检查地访问ArraySize?如果用户输入负数会发生什么?为什么使用__int32而不是size_t或int32_t(非编译器特定且在标准中可用)?你如何退出while(1)循环?为什么要使用数组,当您有可用的std::vector来承担内存管理的负担?