我试图从向量中删除一个元素(如果它存在于其中):
use std::collections::HashMap;
fn test(map: HashMap<String, Vec<String>>, department: String, employee: String) {
let &mut list = map.get(&department).unwrap();
let index = list.iter().position(|x| x == &employee);
match index {
Some(i) => {
list.remove(i);
},
None => {
println!("No records of {} in {}!", &employee, &department);
},
}
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
use std::collections::HashMap;
fn test(map: HashMap<String, Vec<String>>, department: String, employee: String) {
let &mut list = map.get(&department).unwrap();
let index = list.iter().position(|x| x == &employee);
match index {
Some(i) => {
list.remove(i);
},
None => …Run Code Online (Sandbox Code Playgroud) 考虑一个简单的情况,例如在 BST 中查找第 k 个最小元素。
在我下面的解决方案中:
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
i = 0
ans = -1
def traverse_inorder(root):
nonlocal i
nonlocal ans
if not root:
return
traverse_inorder(root.left)
i += 1
if i == k:
ans = root.val
return
traverse_inorder(root.right)
traverse_inorder(root)
return ans
Run Code Online (Sandbox Code Playgroud)
我使用nonlocalfori和是ans好的做法吗?我这样做是为了跟踪到达最左边的节点(最小值)后我遍历了多少个元素。
另一个解决方案是将i和ans作为类的成员变量:
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.i = 0
self.ans = -1
def traverse_inorder(root):
# etc …Run Code Online (Sandbox Code Playgroud) 我一直在阅读“Smashing the Stack for Fun and Profit”,似乎遇到了与其他人过去遇到的类似的问题;但是我无法弄清楚为什么我的代码仍然无法正常工作。
我正在尝试做的事情:
考虑下面的代码:
void function1(int a, int b, int c){
char buffer1[8];
// char buffer2[10];
int *ret;
ret = (int *) buffer1 + 24;
(*ret) += 7;
}
void main() {
int x;
x = 0;
function1(1,2,3);
x = 1;
printf("%d\n", x);
}
Run Code Online (Sandbox Code Playgroud)
该示例的目标是覆盖 *function1 * 的返回地址并跳过 main 中的 x = 1 行。所以,程序应该输出 0 而不是 1。但是,我的输出仍然是 1。所以我不确定我哪里出错了。
使用 gdb 计算返回地址和偏移量
从程序集的 objdump 中:
00000000000006db <main>:
6db: 55 push %rbp
6dc: 48 89 …Run Code Online (Sandbox Code Playgroud)