交换结构体 c++ 向量的内容
Swap contents of vector of structs c++
我有一个由两个字符串、一个长整数和一个整数数组组成的结构向量。创建上述结构后,我将数组中的每个元素初始化为 0。我的问题是,我将如何为数组中的每个元素分配不同的值?我尝试使用 swap 和赋值,但它们更多地用于拥有两个 1 维向量,而不是 2 维向量,我只想在给定时间更改某个结构中的值。请帮忙?谢谢!
如果你想看一些代码,这是我目前所拥有的:
//this is my struct
typedef struct {
string lastName;
string firstName;
long int gNumber;
int grades[12];
} student;
//this function takes data from a file, fills it into a struct, then pushes back into //vector
bool loadStudentData( vector<student> &studentRecords, ifstream *inFile, student tempStudent) {
int idx = 0;
stringstream fileLine;
string line;
bool isLoaded = true;
char letterInGNumber;
while (getline(*inFile, line)) {
fileLine << line;
getline(fileLine, tempStudent.lastName, ',');
getline(fileLine, tempStudent.firstName, ',');
fileLine >> letterInGNumber;
fileLine >> tempStudent.gNumber;
for (idx = 0; idx <= 11; idx++) {
tempStudent.grades[idx] = 0;
}
studentRecords.push_back(tempStudent);
fileLine.flush();
}
return isLoaded;
}
//this function is trying to take things from a second file, and if the Gnumber(the //long int) is found in the vector then assign values to the grade array
void loadClassData(vector<student> &studentRecords, ifstream *inFile) {
int idx = 0, idxTwo = 0, idxThree = 0;
long int tempGNumber = 0;
stringstream fileLine;
vector<long int> gNumbers;
bool numberFound = false;
char letterInGNumber;
string line;
while (getline(*inFile, line)) {
idx++;
numberFound = false;
fileLine << line;
fileLine >> letterInGNumber;
fileLine >> tempGNumber;
for (idxTwo = 0; idxTwo <= studentRecords.size(); idxTwo++) {
if (studentRecords[idxTwo].gNumber == tempGNumber) {
numberFound = true;
break;
}
}
if (numberFound) {
for (idxThree = 0; idxThree <= 11; idxThree++) {
//fileLine >> studentRecords[idx].grades[idxThree];
/**********here is the problem, I don't know how to assign the grade values******/
}
}
else {
cout << "G Number could not be found!" << endl << endl;
}
fileLine.flush();
}
return;
}
有人吗?请?
相反,
您应该做的是定义一个运算符>>重载并读取它。例如
//assume the following structure when reading in the data from file
// firstName lastName N n1 n2 n3 ... nN
ostream& operator>>(ostream& stream, student& s){
stream >> s.firstName;
stream >> s.lastName;
stream >> s.gNumber
for(int i = 0; i < s.gNumber; ++i){
stream >> s.grades[i];
}
}
//... in main
student temp;
std::vector<student> studentList;
while(inFile >> temp) studentList.push_back(temp);
相关文章:
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 如何使用结构体的向量数组?
- 如何使用迭代器指向结构体c++的向量
- 创建结构体向量,表达式:向量下标超出范围
- C++ push_back() 一个结构体到一个向量中
- 使用 boost::p ython,如何将结构体向量作为字典列表返回给 Python
- 交换结构体 c++ 向量的内容
- Vector::erase()也擦除结构体的成员向量
- 如何在结构体中传递指向CURL的指针到向量
- 对的向量和包含两个元素的结构体的向量的内存布局的区别- c++ /STL
- 指向结构体的向量指针错误
- 存储结构体的向量
- 列表排序和结构体向量排序之间的性能差距.c++
- 打印结构体的向量时的奇怪行为
- 带有指针的结构体向量
- 结构体向量的问题:解约束迭代器(可能很容易)
- 具有动态分配成员的结构体的向量
- 结构体初始化的向量
- PTR到结构体和PTR到结构体的向量的模板方法专门化
- 在其他函数中对结构体的向量和向量部分进行排序