我正在制作一个向量程序,该程序每次应该产生3个不同的向量。
这是我到目前为止的代码:
GenerateVector.h文件:
#ifndef Vector_GenerateVector_h
#define Vector_GenerateVector_h
#endif
#include <string>
#include <sstream>
#include <vector>
using namespace std;
class FourVector
{
int x, y, z, t;
public:
FourVector (int a, int b, int c, int d);
int getX() {return x;}
int getY() {return y;}
int getZ() {return z;}
int getT() {return t;}
};
FourVector::FourVector (int a, int b, int c, int d) {
x = a;
y = b;
z = c;
t = d;
}
string toString(FourVector vec) //get vector function
{
ostringstream s; //making a new string stream
s << "("<< vec.getX() << ", " << vec.getY() << ", " << vec.getZ() << ", " << vec.getT() << ")"; // append to string stream
string combinedString = s.str(); //cast string stream to a string
return combinedString; //return string.
}
FourVector genVector()
{
int x = rand() % 10;
int y = rand() % 10;
int z = rand() % 10;
int t = rand() % 10;
FourVector v (x, y, z, t);
return v;
}
vector<FourVector> createArrayFourVectors()
{
vector<FourVector> vecs; //create array of threevectors.
for (int i = 0; i < 3; i++) {
FourVector v = genVector();
vecs.assign(i, v); // assign threevectors to the array to fill it up.
}
return vecs;
}
main.cpp文件:
#include <iostream>
#include "GenerateVector.h"
using namespace std;
int main(int argc, const char * argv[])
{
int seed = static_cast<int>(time(nullptr));
srand(seed);
vector<FourVector> v = createArrayFourVectors();
for (int i = 0; i < 3; i++) {
FourVector tv = v[i];
cout << toString(tv) << endl;
}
}
(5、1、4、8)
(5、1、4、8)
(0,0,0,0)
程序以退出代码结束:0
第一个问题是:我不明白为什么只产生2个向量而不是3个向量。
第二个问题是:为什么向量1和向量2总是相同?在主要功能的开头,我仅使用srand()一次,但仍然遇到这个问题。我认为我的计算机太快了,无法及时更改以产生另一组随机数,但是尝试插入usleep(1000000)并没有什么区别。
任何帮助,将不胜感激!
问题出在vecs.assign(i, v);
。这种形式assign
采用一个整数和一个对象,并将向量设置为等于该对象的副本数。您有一个遍历i
值0、1和2的循环,因此在循环的最后一次迭代中,将设置FourVector
对象的两个副本。这意味着的前两个元素vec
将是相同的副本,向量的长度将是2
,超出此范围的任何访问尝试都将是未定义的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句