首先,正如其他人建议的那样,使用std::vector<std::vector<int>>。它会让事情变得简单得多。
#include <vector>
typedef std::vector<int> IntVector;
typedef std::vector<IntVector> IntVector2D;
所以我们的类型是IntVector2D。 (我定义了后面要使用的一维向量)
接下来,我们要设置一个循环,一次读取一行,解析该行,并将在该行中找到的 int 存储在矩阵的一行中。为此,我们可以将该行读入字符串,然后使用istringstream 进行解析。
最后,对于存储的每一行,我们根据您的随机数函数将更改应用于行上的每个项目。
以下是所有这些的示例:
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <iostream>
typedef std::vector<int> IntVector;
typedef std::vector<IntVector> IntVector2D;
using namespace std;
// random number function to apply
int ApplyRand(int num)
{ return num + rand() - RAND_MAX/2; }
void OutputMatrix(const IntVector2D& m)
{
cout << "\n";
IntVector2D::const_iterator it = m.begin();
while (it != m.end())
{
copy(it->begin(), it->end(), ostream_iterator<int>(cout, " "));
cout << "\n";
++it;
}
}
// Transform the numbers in the matrix
void TransformMatrix(IntVector2D& m)
{
IntVector2D::iterator it = m.begin();
while (it != m.end())
{
transform(it->begin(), it->end(), it->begin(), ApplyRand);
++it;
}
}
int main()
{
IntVector2D matrix;
ifstream pFile("test.txt");
string s;
while ( std::getline(pFile, s) )
{
// create empty row on back of matrix
matrix.push_back(IntVector());
IntVector& vBack = matrix.back();
// create an istringstream to parse
istringstream ss(s);
// parse the data, adding each number to the last row of the matrix
copy(istream_iterator<int>(ss), istream_iterator<int>(), back_inserter(vBack));
}
// output the matrix
OutputMatrix(matrix);
// Apply rand to each number
TransformMatrix(matrix);
// output the updated matrix
OutputMatrix(matrix);
}
输出:
283 278 284 290 290 286 273 266 266 266 261 252 246
382 380 379 381 382 379 384 387 385 382 376 365 357
285 282 281 279 276 273 272 264 255 255 247 243 237
196 190 186 183 183 180 179 186 191 195 195 188 187
245 237 226 220 221 222 225 228 234 245 252 264 272
283 278 284 290 290 286 273 266 266 266 261 252 246
-16059 2362 -9765 10407 3076 -373 -4632 13241 10845 8347 -10417 12014 7144826
-6042 -15513 -13007 -4059 -11177 -10563 16395 -1394 -12099 -15854 -15726 -3644
1323 2615 3616 3791 -10660 5616 -1340 -4581 -14259 3784 9531 10159 889
-6293 12510 7614 15122 14133 1470 -11540 -1056 -8481 12065 -9320 9352 11448
16524 16611 3880 -3304 -7439 -6420 11371 -15377 -3833 -13103 6059 -14277 -15823
14006 -7065 -7157 3171 6555 11349 7695 -227 -9388 8253 -772 -1125 14964
注意使用std::copy从istringstream中提取项目,back_inserter负责在矩阵的最后一行调用push_back。
此外,std::transform 的使用允许我们在每个元素上调用一个函数,使用 ApplyRand 作为执行此转换的函数,将元素从原始值“转换”为更改后的值。