1

I have a vector within a vector defined as:

std::vector<std::vector<myObj>> some_list(list_size);

some of the entries in some_list have elements and some don't those that have 3 elements have size 3 those with 4 have size 4 etc. for example:

some_list[0] {size=3}
some_list[1] {size=4}

but at some point there is an empty entry with 0 elements such as:

some_list[14] {size=0}

after which point every entry that follows has size 0 as well.

I am trying to resize my vector so it excludes such entries and is left with only the entries that have elements. But for some reason I can't make it work. Here's what I have:

int snum = 0;

      for (std::vector<std::vector<myObj>>::iterator a_it = a_list.begin(); 
          a_it != a_list.end(); a_it++) {
              while (a_it->size() != 0) {
                  snum++;
              }
      }

a_list.resize(snum);
4

3 回答 3

4

这一行:

while (a_it->size() != 0) {

应该是:

if (a_it->size() != 0) {
于 2013-09-07T16:22:00.323 回答
2

如果您确定第一个空元素之后的所有条目也将为空,则可以使用std::find_if获取第一个空元素的迭代器,然后使用std::vector::erase

#include <algorithm>

bool is_empty(const std::vector<myObj>& v) { return v.empty(); }

v.erase(std::find_if(v.begin(), v.end(), is_empty), v.end() );

或者,如果您支持 C++11,则可以使用 lambda:

v.erase(std::find_if(v.begin(), 
                       v.end(), 
                       [](const std::vector<myObj>& v){ return v.empty(); }), 
        v.end() );

我用的地方vsome_list.

否则,如果最后不是所有的空条目,您可以使用具有合适功能的擦除删除习惯用法删除具有零元素的条目。

v.erase(std::remove_if(v.begin(), v.end(), is_empty), v.end() );
于 2013-09-07T16:22:23.940 回答
0

您应该首先删除空元素。您可以使用现成的算法:

#include <algorithm>
#include <functional>

some_list.erase(std::remove_if(some_list.begin(), some_list.end(),
                               std::mem_fn(&std::vector<myObj>::empty),
                some_list.end());

然后你可以调整大小:some_list.resize(N)。事实上,如果你无论如何都希望新元素为空,你可以跳过这erase一步,只做remove_if部分。

于 2013-09-07T16:22:42.920 回答