【发布时间】:2016-04-15 06:00:55
【问题描述】:
自从我使用 C++ 以来已经有一段时间了,我正在尝试编写一个简短的函数来处理格式为 "{(0.00, 0.00); (1.00, 0.00); (0.00, 1.00); (1.00, 1.00)}" 到自定义类中。
然而,我正在努力成功返回我从函数的自定义类中的字符串中提取的值。
在下面找到相关代码:
class TwoDMap
{
private:
int dim, num_verts;
std::vector<float> int_array;
public:
TwoDMap (int num_vertices, int dimension);
float getData(int num_vert, int dim);
void addData(float value);
};
TwoDMap::TwoDMap(int num_vertices, int dimension)
{
num_verts = num_vertices;
dim = dimension;
int_array.reserve(num_vertices * dimension);
}
float TwoDMap::getData(int num_vert, int dimension)
{
return int_array[(num_vert * dim) + dimension];
}
void TwoDMap::addData(float value)
{
int_array.push_back(value);
}
void processStringVertex(TwoDMap return_vector, int vert_index, int dimension, std::string input_vertex)
{
//Process a single portion of the string and call the addData method
//to add individual floats to the map
}
TwoDMap processStringVector(int dimension, int num_vertices, std::string input_vector)
{
TwoDMap array2D (num_vertices, dimension);
//Process the whole string, calling the processStringVertex method
//and passing in the variable array2D
return array2D;
}
int main()
{
std::string v = "{(0.00, 0.00); (1.00, 0.00); (0.00, 1.00); (1.00, 1.00)}";
int dim = 2;
int num_verts = 4;
TwoDMap vect = processStringVector (dim, num_verts, v);
for( int i = 0; i < num_verts; i = i + 1)
{
for( int j = 0; j < dim; j = j + 1)
{
std::cout << vect.getData(i, j) << std::endl;
}
}
}
我的字符串算术都正确返回,代码编译并运行,但我的 TwoDMap 类在主方法循环中返回全 0,即使正确的值被传递给 addData 方法。
经过大量的故障排除和调试,我认为问题在于我如何传递自定义类 TwoDMap。但是,在尝试了几种变体之后(传递二维数组、传递一维数组、传递指向数组的指针、传递带有内部一维数组的 TwoDMap 以及 TwoDMap 的这种变体),我不知道以这种方式执行操作的正确方法。
如何从以这种方式编写的函数中传递一个类似列表的对象?
谢谢!
亚历克斯
【问题讨论】:
-
您没有显示足够的代码。
addData没有在您发布的代码中被调用。您尝试减少代码很好,但您需要提供足够的代码,以便其他人可以编译它并重现问题。 -
另外,在
processStringVector()中,第一行是一个函数声明。这里没有理由返回一个函数。
标签: c++ arrays class vector return