【问题标题】:how to pushback on a vector of vectors?如何推回向量的向量?
【发布时间】:2013-03-18 19:03:30
【问题描述】:

我正在接受 20 行输入。我想用空格分隔每一行的内容并将其放入向量向量中。如何制作向量的向量?我很难把它推回去......

我的输入文件:

Mary had a little lamb
lalala up the hill
the sun is up

矢量应该看起来像这样。

ROW 0: {"Mary","had", "a","little","lamb"}
ROW 1: {"lalala","up","the","hill"}

这是我的代码....

string line; 
vector <vector<string> > big;
string buf;
for (int i = 0; i < 20; i++){
    getline(cin, line);
    stringstream ss(line);

    while (ss >> buf){
        (big[i]).push_back(buf);
    }
}

【问题讨论】:

  • 你那里有一个向量向量。你的代码有什么问题?
  • @AndyProwl 越界访问(假设代码是真实代码的良好表示)。
  • @juanchopanza:哦,对了 :) 好收获
  • +vote for mary had a little lamb而不是foo/bar

标签: c++ vector


【解决方案1】:

代码是正确的,但是你的向量中有零个元素,所以你不能访问big[i]

在循环之前设置向量大小,可以在构造函数中,也可以这样:

big.resize(ruleNum);

或者,您可以在每个循环步骤中推送一个空向量:

big.push_back( vector<string>() );

big[i] 也不需要括号。

【讨论】:

    【解决方案2】:

    你可以从大小为ruleNum的向量开始

    vector <vector<string> > big(ruleNum);
    

    这将包含 ruleNum 空的 vector&lt;string&gt; 元素。然后,您可以将元素推回每个元素中,就像您当前在您发布的示例中所做的那样。

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

      string line; 
      vector <vector<string> > big;  //BTW:In C++11, you can skip the space between > and >
      
      string currStr;
      for (int i = 0; i < ruleNum; i++){
          getline(cin, line);
          stringstream ss(line);
          vector<string> buf;
          while (ss >> currStr){
             buf.push_back(buf);
          }
          big.push_back(buf);
      }
      

      【讨论】:

      • 不需要在外循环外声明buf,事实上你忘记在循环内清除它。
      • @KonradRudolph 你说得对,我很粗心,代码刚刚更新。谢谢!
      • 哈哈,现在你在做不必要的工作,向量每次都重新定义,因此为空,无需clear()它。
      • @KonradRudolph 再次更新,但将 clear() 放在那里不会损害正确性。我同意这是多余的。谢谢!
      • 将 buf 移动到 big 有意义吗?还是发生复制省略的情况,所以没有理由?
      【解决方案4】:
                    vector<vector<string> > v;
      

      为了 push_back 成向量的向量,我们将 push_back 内部向量中的字符串和 push_back 内部向量到外部向量。

      展示其实现的简单代码:

      vector<vector<string> > v;
      vector<string> s;
      
      s.push_back("Stack");
      s.push_back("oveflow");`
      s.push_back("c++");
      // now push_back the entire vector "s" into "v"
      v.push_back(s);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多