c++ - 从vector中删除元素,vector被struct填充

标签 c++ vector struct erase

像这样:

struct mystruct 
{
  char straddr[size];
  int port;
  int id;
  .......
};

mystruct s1={......};
mystruct s2={......};
mystruct s3={......};

vector test;
test.emplace_back(s1);
test.emplace_back(s2);
test.emplace_back(s3);

现在我想删除 straddr="abc"和 port = 1001 的元素。 我应该怎么办? 我不想这样做。

    for(auto it = test.begin();it != test.end();)
   {
      if(it->port == port && 0 == strcmp(it->straddr,straddr))
         it = test.erase(it);
     else
        it++;
   }

最佳答案

首先,使用 std::string 而不是 char [size] 这样就可以使用 == 而不是 strcmp 和其他类似的 C 字符串函数。

然后使用 std::remove_if()erase() 作为:

test.erase (
    std::remove_if(
        test.begin(), 
        test.end(), 
        [](mystruct const & s) { 
            return s.port == 1001 && s.straddr == "abc"; 
        }
    ), 
    test.end()
);

这是您问题的惯用解决方案,您可以在此处阅读更多相关信息:

请注意,此解决方案将从谓词返回 true 的容器中删除所有元素。然而,如果事先知道最多有一个项目匹配谓词,那么 std::find_if 伴随着 erase() 会更快:

auto it = std::find_if(
             test.begin(), 
             test.end(), 
             [](mystruct const & s) { 
               return s.port == 1001 && s.straddr == "abc"; 
             }
          );
if(it != test.end())//make sure you dont pass end() iterator.
    test.erase(it); 

希望对您有所帮助。

关于c++ - 从vector中删除元素,vector被struct填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35715987/

相关文章:

c++ - GCC 可以在不生成目标文件或可执行文件的情况下编译和运行源代码吗?

java - 将字符串转换为 vector

math - 如何计算两个归一化向量和向上方向之间的角度?

使用 fork 创建子项并出现段错误(核心转储)

c++ - 转换宏参数名称以用作 C++ 中的函数

c++ - c++11标准中关于可变参数模板的困惑

c++ - vector 下标超出范围 - 冒泡排序 - 改进

c - 在 Visual Studio 中拆分文件

c++ - 创建指向结构数组指针数组的指针,然后访问结构中的变量

oop - 在 Golang 中返回一个结构