使用对std::向量的某些元素的引用,或这些元素在向量中的位置,对它们进行迭代

Use references to some elements of a std::vector, or the position of such elements in the vector, to iterate over them

本文关键字:元素 向量 位置 迭代 引用 std      更新时间:2023-10-16

在我正在编写的应用程序中,我将数据存储在等对象中

std::vector<my_struct> db;

我经常需要引用它们的一些元素,并使用std::集,在其中我将它们的位置存储在向量中(不会改变)

std::set<int> elements_i_like; 

然后,我用访问数据库元素

for ( auto it = elements_i_like.begin(); it!=elements_i_like.end(); it++){
    db[*it].do_something();
}

不过,我有一个疑问,在性能方面,不将元素的索引存储在向量中,而是直接引用它们会更好吗?

std::vector<my_struct> db; //where i store the data (edit form original question)
std::set<my_struct&> elements_i_like;//reference to the specific structs, stored in the vector, that i want to iterate on

并进行

for( auto it= elements_i_like.begin(); it!=elements_i_like.end(); it++){
    (*it).do_something();
}

这样做会有什么缺点吗?谢谢

您不能将引用存储在容器中,在任何情况下,即使编译器/语言允许,您仍然需要两个解引用来评估每个迭代。

顺便说一句,如果C++11可用,您可以将循环重写为:

for(auto& elem : elements_i_like)
    elem.do_something();