C++ 在类构造函数中拆分字符串
我有一个包含两个数据成员的类:size和一个int数组(动态分配)。该类的目的是创建一个大小为的数组并用值填充它。任务是创建一个以字符串作为参数的构造函数,但是字符串看起来像这样:“12 | 13 | 14 | 15”等等。我已经搜索过了,但是所有的解决方案都有点太复杂了,因为它们涉及向量,我们还没有开始向量。我基本上想把这些数字放到整数数组中,1乘1,并找出数组的大小。我该怎么做?我试图搞乱getline和stringstream,但这给了我很多错误。我的代码看起来像这样C++ 在类构造函数中拆分字符串,c++,string,split,stringstream,C++,String,Split,Stringstream,我有一个包含两个数据成员的类:size和一个int数组(动态分配)。该类的目的是创建一个大小为的数组并用值填充它。任务是创建一个以字符串作为参数的构造函数,但是字符串看起来像这样:“12 | 13 | 14 | 15”等等。我已经搜索过了,但是所有的解决方案都有点太复杂了,因为它们涉及向量,我们还没有开始向量。我基本上想把这些数字放到整数数组中,1乘1,并找出数组的大小。我该怎么做?我试图搞乱getline和stringstream,但这给了我很多错误。我的代码看起来像这样 #include &
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class IntArrays {
private:
static int objcount;
int size;
public:
int *arrayints;
const static int objcountf();
IntArrays(int);
IntArrays(const IntArrays &p){
size = p.size;
for (int i = 0;i <size;i++){
arrayints[i] = p.arrayints[i];
}
}
IntArrays(std::string f){
// ignore the other constructors, this is the constructor that is giving me trouble
int counter =0;
istringstream inStream(f);
string newstring;
while (getline(iss,newstring, '|')){
arrayints[counter] = stoi(newstring);
counter++;}
void enternums();
(note that this is only the header file, and that the current string constructor I have there does not work.
#包括
#包括
#包括
使用名称空间std;
班级安排{
私人:
静态内部对象计数;
整数大小;
公众:
int*arrayints;
常量static int objcountf();
IntArrays(int);
安装(施工安装和安装){
尺寸=p.size;
对于(inti=0;i我将尝试对该=p进行递归
对不起,我不能提供C++版本= p。
我想这是一个java版本
list parse(string data, list base) {
if (data.length > 0) {
string s = data.subStr(0,1);
if (s == "|") {
base.push(0); //set the initial value for a new value
} else {
int i = parseInt(s);
int result = base.pop()*10 + i; //recalculate the result
base.push(result);
}
return parse(data.subStr(1),base); //recursion
} else {
return base; //return the result
}
}
正如Joachim所指出的,您没有初始化指针。不幸的是,在分配之前,您没有数组的大小,因此剩下一些解决方案:
处理输入两次(如果有大量条目,则非常糟糕);在第一次处理时,对输入进行计数。然后分配数组,然后再次将其读取到分配的数组中
将输入读入链接列表;列表中的每个元素都会包含一个值和下一个元素的地址
预先分配一个内存块,并希望它足够大以读取整个数组。如果不是,则重新分配一个较大的内存块,并将已读取的值复制到其中,然后丢弃初始内存块(这就是std::vector所做的)
此代码是我的版本。我更喜欢使用向量
,而不是原始数组
类别定义:
class IntArrays {
public:
IntArrays(const string&, const char&);
const vector<int>& data() { return _data; }
const int size() { return _data.size(); }
private:
vector<int> _data;
};
然后我们就使用这个类:
IntArrays a("1|4|9|6|69", '|');
vector<int> da = a.data();
IntArrays b("1,4,9,6,69", ',');
vector<int> db = b.data();
IntArrays a(“1 | 4 | 9 | 6 | 69”,“|”);
向量da=a.data();
图b(“1,4,9,6,69”和“,”);
向量db=b.data();
你有你的指针数组,但是你从来没有初始化过它。这当然会导致你取消引用它。
IntArrays a("1|4|9|6|69", '|');
vector<int> da = a.data();
IntArrays b("1,4,9,6,69", ',');
vector<int> db = b.data();