使用对std::向量的某些元素的引用,或这些元素在向量中的位置,对它们进行迭代
Use references to some elements of a std::vector, or the position of such elements in the vector, to iterate over them
在我正在编写的应用程序中,我将数据存储在等对象中
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();
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?