21xrx.com
2024-09-19 09:39:13 Thursday
登录
文章检索 我的文章 写文章
C++中的container_of宏的使用
2023-07-09 09:38:00 深夜i     --     --
C++ container_of宏 使用方式

在C++编程中,container_of宏是一个特别有用的工具,它允许程序员从一个已知变量的指针中获取容器对象的指针。这个宏类似于C语言中的offsetof宏,但是C++的container_of宏更加灵活和安全。

在C++的STL中,我们经常使用各种容器,如vector、list和map。在STL中,容器对象是通过使用指针来实现的。这个指针指向一个特定的内存位置,通常称为容器对象的头部。container_of宏可以使用这个指针来找到容器对象的指针。

此外,当我们需要在容器对象中访问元素时,通常会使用迭代器。迭代器实际上是一个指代元素的指针。我们可以通过使用container_of宏,在迭代器中获取容器对象的指针,这使得我们可以轻松地从容器中获取元素。

下面是一个简单的示例,演示如何使用container_of宏来获取容器对象的指针:


#include <iostream>

#include <vector>

#define container_of(ptr, type, member) (type*)((char*)(ptr) - offsetof(type, member))

struct Person

  std::string name;

  int age;

;

int main()

{

  std::vector<Person> people = { 25, "Bob", 35 };

  for (auto it = people.begin(); it != people.end(); ++it)

  {

    Person* person = container_of(&*it, Person, age);

    std::cout << person->name << " is " << person->age << " years old." << std::endl;

  }

  return 0;

}

在这个示例中,我们定义了一个包含字符串名称和整数年龄的Person结构体,并创建了一个Person类型的vector对象来存储若干个Person对象。我们在vector上遍历时使用了迭代器,通过container_of宏获取了Person对象的指针,并输出了每个人的名字和年龄。

总之,container_of宏是一种非常有用的工具,可以在C++编程中快速、灵活和安全地获取容器对象的指针。如果你是一个C++程序员,使用container_of宏可以提高你的开发效率和代码质量。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章