在C ++中使用vector的正确方法是什么?

时间:2019-03-18 03:06:12

标签: c++ c++11 vector stl

我正在尝试通过以下代码找到使用vector的正确方法:

#include <vector>
using namespace std;

void f(int size) {
      vector<int> v;
      v.reserve(size);

      v[0] = 1; // OK

      vector<vector<int> > vv;
      vv.reserve(size);

      // vv.push_back(v); // everything is OK with this

      vv[0].push_back(1); // Crash
      vv[0] = {1}; // Crash
}

int main() {
    f(3);
}

但是我不知道为什么不能使用vector的向量与vector相同的方式?为什么我不能通过push_back一个向量直接使用vv(向量的向量)的成员?

2 个答案:

答案 0 :(得分:0)

请参考更新后的示例。可能有助于澄清:

#include <vector>
#include <stdexcept>

void f(int size) 
{
    // don't use using namespace standard at global scope.
    // if you must use it, use it at the tightest possible scope
    // for better, only bring in the names you need
    using std::vector;

    // creates an empty vector with size() == 0 and capacity() == 0
    vector<int> v;

    // this reserves storage, it does not create objects in v or extens its size()
    v.reserve(size);   
    // v.capacity() is now >= size
    // in this example, this step is actually un-necessary because...

    // ... a resize will increase capacity() if necessary
    v.resize(size);

    // there is still possible UB here, if size == 0.
    // we should check for that...
    if (v.size() < 1)
        throw std::out_of_range("size is less than 1");
    v[0] = 1; // This is now OK

    // ...which is essentially equivalent to this...
    v.at(0) = 1;

    // create an empty vector of vectors
    // vv.size() == vv.capacity() == 0
    vector<vector<int> > vv;
    vv.reserve(size);
    // now vv.size() == 0 and vv.capacity() >= size

    // this would result in:
    // vv.size() == 1, vv.capacity() >= max(vv.size(), size);
    // vv.push_back(v); // everything is OK with this

    if(1)
    {
        // at the moment, vv[0] results in UB because .size() is zero
        // so lets's add an entry in vv
        vv.resize(1);
        // vv.size() == 1, vv.capacity() >= max(vv.size(), size);

        // these are now valid
        vv[0].push_back(1); 
        vv[0] = {1}; 
    }
    else
    {
        // this would also be ok
        auto make_vector = [] {
            auto va = vector<int>();
            va.push_back(1);
            return va;
        };
        vv.push_back(make_vector());

        // as would this
        vv.emplace_back(std::vector({1}));
    }
}

int main() {
    f(3);
}

答案 1 :(得分:-1)

我不确定您的问题。 这是向量使用的方式。 希望它能对您有所帮助。

#include<iostream>
#include <vector>

using namespace std;

 void f(int size) {
  vector<int> v;
  v.reserve(size);
for(int i=0;i<3;i++)
 {
 v[i] = i+1; // OK
 }

  vector<vector<int> > vv;
  vv.reserve(size);
  cout<<v[0]<<"/"<<v[1]<<endl;
for(int i=0;i<3;i++)
 {
   vv[0].push_back(v[i]);
 }
  vv[1].push_back(10); // Crash
  vv[0] = {1}; // Crash
  cout<<"vv="<<vv[0][0]<<"/"<<vv[0][1]<<"/"<<vv[1][0];
}

int main() {

f(3);
}