在C ++ 11中初始化向量向量

时间:2014-07-06 20:05:20

标签: c++ c++11 vector

我正在尝试按如下方式创建2D矢量:

//create vector of vectors with 7 elements and 4 fields
vector<vector<string>> trainingData(4, vector<string>(7));
vector<string> age;
vector<string> has_job;
vector<string> own_house;
vector<string> credit_rating;

age = {"young", "young", "middle", "middle", "middle", "old", "old"};
has_job = {"no", "no", "no", "no", "yes", "no", "no"};
own_house = {"no", "no", "no", "no", "yes", "yes", "yes"};
credit_rating = {"fair", "good", "fair", "good", "good", "excellent", "good"};

trainingData = {age, has_job, own_house, credit_rating};

这样初始化是对的吗?我可以根据字段名列出数据,但我不能删除一个向量(例如通过调用trainingData.erase(trainingData.begin()+ 1)来删除has_job向量)

2 个答案:

答案 0 :(得分:3)

我同意Kerrek SB的回答,它解决了手头的问题。我想你可能想要更进一步,制作结构的training_data变量向量,而不是字符串向量的向量。

enum class CreditRating { FAIR, GOOD, EXCELLENT };
enum class Age { YOUNG, MIDDLE, OLD };

// Make plain-old-data, so that you can initialize using aggregate initialization
struct Applicant 
{
  Age age;
  bool has_job;
  bool owns_house;
  CreditRating credit_rating;
};

const std::vector<Applicant> training_data{
        { Age::YOUNG, false, false, CreditRating::FAIR },
        { Age::YOUNG, false, false, CreditRating::GOOD },
        // [...]
        {   Age::OLD, false,  true, CreditRating::GOOD } };

// Use training_data

答案 1 :(得分:2)

这看起来过于笨拙和迂回。您可以一次初始化带有所需内容的向量,如果您愿意,甚至可以将其设为const:

const std::vector<std::vector<std::string>> trainingData
  { { "young", "young", "middle", "middle", "middle", "old",       "old"  }
  , { "no",    "no",    "no",     "no",     "yes",    "no",        "no"   }
  , { "no",    "no",    "no",     "no",     "yes",    "yes",       "yes"  }
  , { "fair",  "good",  "fair",   "good",   "good",   "excellent", "good" }
  } ;