gpt4 book ai didi

c++ - 存储 std::list 元素的地址;内存

转载 作者:搜寻专家 更新时间:2023-10-31 02:02:13 33 4
gpt4 key购买 nike

我正在创建结构元素的 std::list。根据特定标准,我想将列表中的几个元素的地址(因为这些地址不会更改(?))存储到 std::vector 中,以便在其他用途​​中快速访问。下面给出了一个例子

#include <iostream>
#include <vector>
#include <list>

struct Astruct{
double x[2];
int rank;
};


int main(int argc, char *argv[]) {


std::list<Astruct> ants;
std::vector< Astruct* > ptr;

for (auto i = 0; i != 20; ++i) {
Astruct local;
local.x[0] = 1.1;
local.x[1] = 1.2;
local.rank = i;
// put in list
ants.push_back(local);


// store address of odd numbers
// rather than temperory address, permenent address from list is needed
if(local.rank %2 == 0) ptr.push_back(&local);
}

// print the selected elements using addresses from the list
for(int num = 0; num != ptr.size(); num++){
Astruct *local;
local = ptr.at(num);
std::cout << " rank " << local->rank << "\n";
}

/*
// quick way to check whether certain address (eg 3rd element) exists in the std::vector
std::list<Astruct>::iterator it = ants.begin();
std::advance(it , 2);
for(int num = 0; num != ptr.size(); num++){
if(it == ptr.at(num)) std::cout << " exists in vector \n " ;
}

*/
// print memory in bytes for all variables
std::cout << " sizeof Astruct " << sizeof(Astruct) << "\n";
std::cout << " sizeof ants " << sizeof(ants) << "\n";
std::cout << " sizeof ptr " << sizeof(ptr) << "\n";
}
  1. 从列表中访问特定元素的地址的方法是什么?
  2. 向列表中添加元素是一种有效的方法吗? (在第一个 for 循环中)
  3. 检查 vector 中是否存在特定地址的最快方法是什么? (显示在评论区)
  4. 这里如何确定不同变量的内存大小(以字节为单位)? (代码结束)

谢谢。

最佳答案

  1. 从列表中访问特定元素的地址的方法是什么?

    • address=&(*iterator);
  2. 向列表中添加元素是一种有效的方法吗? (在第一个 for 循环中)

    • 第一个循环根本不使用列表! (啊,好的,在编辑之后它会)
    • 存储在 vector 中的所有地址都引用一个局部变量,该变量在每次迭代后消失;这是未定义的行为(很可能,但不能确定,所有这些地址都是相同的)
  3. 检查 vector 中是否存在某个地址的最快方法是什么? (在评论区显示)

    • 通常std::find()来自 <algorithm>是合适的。
  4. 这里如何确定不同变量的内存大小(以字节为单位)? (代码结束)

    • std::cout << " sizeof Astruct " << sizeof(Astruct) << "\n";还可以
    • std::cout << " sizeof ants " << size(ants)*sizeof(Astruct) << "\n";是一个近似值,因为我们不知道列表及其节点的开销
    • std::cout << " sizeof ptr " << size(ptr)*sizeof(Astruct *) << "\n";是一个近似值,因为我们不知道 vector 的开销

关于c++ - 存储 std::list 元素的地址;内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57723590/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com