我通常更喜欢constness,但最近遇到了一个与const迭代器的难题,震动了我的const态度让我很烦恼:
MyList::const_iterator find( const MyList & list, int identifier )
{
// do some stuff to find identifier
return retConstItor; // has to be const_iterator because list is const
}
Run Code Online (Sandbox Code Playgroud)
我想在这里表达,当然,这个想法是,在列表传递不能/ willnot改变,但一旦我做出的排行榜引用常量然后我必须使用"常量性的,然后阻止我与做任何事情对矫正结果(这是有道理的).
那么,解决方案是放弃制作传入的容器引用const,还是我错过了另一种可能性?
这一直是我对const的秘密保留:即使你正确使用它,它也可能产生在没有好/干净解决方案的情况下不应该出现的问题,尽管我认识到这更常见于const和迭代器的概念.
编辑:我非常清楚为什么你不能也不应该为const容器返回一个非const迭代器.我的问题是,虽然我要为我的容器中,按引用传递在编译时检查,我还是想找到一种方法,传回的东西的位置,并用它来修改列表的非const版本.正如其中一个答案中所提到的,可以通过"提前"提取这种位置概念,但是凌乱/低效.
std :: set_union及其亲属需要两对迭代器来操作集合.这很棒,因为它是最灵活的事情.然而,他们很容易就能够提供额外的便利功能,这些功能在80%的典型用途中会更加优雅.
例如:
template<typename ContainerType, typename OutputIterator>
OutputIterator set_union( const ContainerType & container1,
const ContainerType & container2,
OutputIterator & result )
{
return std::set_union( container1.begin(), container1.end(),
container2.begin(), container2.end(),
result );
}
Run Code Online (Sandbox Code Playgroud)
会转:
std::set_union( mathStudents.begin(), mathStudents.end(),
physicsStudents.begin(), physicsStudents.end(),
students.begin() );
Run Code Online (Sandbox Code Playgroud)
成:
std::set_union( mathStudents, physicsStudents, students.begin() );
Run Code Online (Sandbox Code Playgroud)
所以:
是否有这样的便利功能隐藏在我找不到的地方?
如果没有,有什么理由可以将它排除在STL之外吗?
在boost中是否还有更全功能的集合库?(我找不到一个)
我当然可以总是将我的实现放在某个实用程序库中,但是很难将这些内容组织起来,以便它们可以在所有项目中使用,但不会被错误地聚集在一起.
与同事讨论的结果我最终编写了测试std::vectorvs原始动态分配数组的基准测试,结果出人意料.
我的测试如下:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * const intArray = new int[ numInts ];
++intVector[0]; // force access to affect optimization
++intArray[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intArray[i];
}
delete[] intArray;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
和:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main() …Run Code Online (Sandbox Code Playgroud) (我正在解决的问题涉及我无法改变的第三方库)
#include <list>
//Third party lib namespace
namespace foo
{
typedef int SomeType;
}
//my namespace
namespace mycompany
{
namespace groo
{
typedef std::list<foo::SomeType> SomeTypeList;
}
namespace foo
{
typedef std::list<foo::SomeType> SomeTypeList;
}
}
int main() { return 0; }
Run Code Online (Sandbox Code Playgroud)
尝试编译它会产生错误:
error: 'SomeType' is not a member of 'mycompany::foo'
Run Code Online (Sandbox Code Playgroud)
从groo工作访问就好了.你怎么访问浅foo的mycompany::foo?
(我会自己回答这个问题,但我想发布问题以防其他人有同样的问题)
如何检测段内故障是否由内存不足情况引起?
我有一个段错误,无法通过valgrind和duma/efence进行诊断,因为它似乎会自动崩溃这些工具(Valgrind"发生了一次",duma:"mprotect()失败:无法分配内存")
应用程序(Gazebo)只是崩溃了一个段错误,而堆栈跟踪似乎没有提供很多关于原因的提示.
TLDR:是否有一个简单的工具或方法来确认或排除内存不足的情况是导致段错误的原因?
(top在崩溃前没有显示过多的内存使用量)
c++ ×4
stl ×3
boost ×1
const ×1
iterator ×1
linux ×1
namespaces ×1
performance ×1
profiling ×1
scope ×1
set ×1
set-theory ×1
vector ×1