[ROS/C++] Using smart pointers in containers

2014年8月17日 17:35

Problem Description:

The memory leak problem was found when I tested the ROS simulation of a large number of robots, say, 50. Basically I have one simulator node and 50 robot controller nodes. Occasionally after running the program for a while, the simulator node may throw a bad_alloc exception and then terminated.

Tags: c++ ROS
评论(49) 阅读(5834)

6,23,39二叉树(1) 打印,深度,重建 Binary Search Tree (1)

2013年10月05日 16:32

Binary Search Tree(BST) 是很基础的数据结构,书中不止一条关于binary tree的题目,所以这里集中讨论三个问题。

首先是BST的实现,目前我参考了[1],[2],[3]的程序,总结写出了一个基本的类,包含insert, remove, destroy_tree, search等函数。

花时间最多的是remove函数的实现。难点是当要移除的节点有2个子节点。我采用了[2]中的程序,[2]中的方法正是[3]中提到的思路。

如图中所示:

Tags: c++
评论(5) 阅读(2744)

5. 逆序打印单向链表 Print linked list reversely using C++ class implementation

2013年10月03日 14:20

书中用struct实现了节点(node):

struct ListNode{
    int m_nValue;
    ListNode* m_pNext;
};

然后用ListNode **head表示链表的头。

个人不喜欢这样表示。我相信现在应该没有多少人愿意去看有“指针的指针”的程序。一个程序中出现指针是很正常的,但是出现“指针的指针”就很讨厌了。属于overuse of pointers。不仅容易出错而且降低程序可读性。还有一点就是这样表示链表明显能看出有C-style。没有充分发挥C++语言良好的封装性。我没用书上的例程。参考了[1]用class实现了list。(注意到[1]中的代码有bug:如果用原程序中的Delete函数从头开始删除节点,那么就会产生segmentation fault)。

Tags: c++
评论(7) 阅读(3255)

4.替换空格

2013年10月03日 13:59

给定一个字符串,实现一个函数把字符串中的每个空格替换成 '%20'。

书中给出了时间为O(n)的算法:

  1. 先遍历字符串长度,得到总长和空格数
  2. 计算替换后的字符串总长度
  3. 双指针实现从尾部向前替换

Tags: c++
评论(8) 阅读(2402)

3.二维数组中的查找

2013年9月30日 17:43

给一个有规律的整数矩阵,每行元素从左到右递增,第列元素从上到下递增。

要求完成一个查找函数,输入为满足以上条件的一个二维数组以及一个整数,判断数组中是否包含此整数。

如:

[tex] \begin{bmatrix}  1 & 2 & 8 & 9 \\ 2 & 4& 9& 12\\ 4 & 7 & 10&13 \\ 6 & 8 & 11& 15\end{bmatrix}[/tex]

查找7应当返回true,查找5应当返回false.

Tags: c++
评论(9) 阅读(2602)