【发布时间】:2017-09-17 02:42:09
【问题描述】:
我的目标是创建一个类型为“TeamS”的向量,即 TeamV。 TeamV 应该有 4 个数据部分。例如:TeamV[0] = 团队 ID、成员 1、成员 2、成员 3。 我找到了一种获取 id 数组并分发到 TeamV 向量的方法。但我不能同时分配 3 个团队成员。我该怎么办?
#include <iostream>
#include <vector>
using namespace std;
const int NUM_TEAMS = 4;
const int NUM_MEMBERS = 3;
struct TeamS{
int ID;
string teamMembers[3];
};
void Initialize (vector <TeamS> & TeamV, const int id[],
const string m[][NUM_MEMBERS], int arraySize){
for (int i = 0; i<NUM_TEAMS;i++){
for (int x=0; x<NUM_TEAMS;x++){
for (int y = 0; y<NUM_MEMBERS;y++){
TeamV.push_back({id[i],m[x][y]});
}
}
}
}
int main(){
vector <TeamS> TeamV; //content of arrays below should go in to this vector
const int ID [NUM_TEAMS] ={ 123, 321, 456, 789};
const string MEMBERS [NUM_TEAMS] [NUM_MEMBERS ] =
{
{"Sarah", "Joe", "John"},
{"Chris", "Kevin", "James"},
{"Tom", "Kim", "Emily"},
{"Jill", "Jason", "Jim"}
};
Initialize(TeamV, ID, MEMBERS, NUM_TEAMS*NUM_MEMBERS);
}
【问题讨论】:
-
你应该做的是将数组成员初始化为
{a, b, c}。 -
喜欢this?还是您一定要复制任意数组?
-
我认为你在这里犯了一个错误:
TeamV.push_back({id[i],m[x][y]})。尽管 TeamS 结构需要 3 个团队成员,但您 push_back 的 ID 和 1 个团队成员(x 和 y 位置)。所以@Drop 的解决方案很好,因为他通过了 TeamS 结构。