gpt4 book ai didi

c++ - 将 remove_if 与 C 空终止字符串一起使用

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:05 26 4
gpt4 key购买 nike

我有一种情况想有效地从 NULL 终止的 char * 中删除一个字符。我可以假设传入的字符串很大(即复制效率不高);但我也可以假设我不需要取消分配未使用的内存。

我想我可以使用 std::remove_if 来完成这个任务(用 NULL 终止符替换返回的迭代器中的字符),并设置以下测试程序以确保我得到语法正确:

#include <algorithm>
#include <iostream>

bool is_bad (const char &c) {
return c == 'a';
}

int main (int argc, char *argv[]) {
char * test1 = "123a45";
int len = 6;
std::cout << test1 << std::endl;
char * new_end = std::remove_if(&test1[0], &test1[len], is_bad);
*new_end = '\0';
std::cout << test1 << std::endl;

return 0;
}

这个程序可以编译,但是,我在 remove_if 的某处遇到了 Segmentation Fault - 这是 gdb 的输出:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400914 in std::remove_copy_if<char*, char*, bool (*)(char const&)> (__first=0x400c2c "45", __last=0x400c2e "", __result=0x400c2b "a45",
__pred=0x4007d8 <is_bad(char const&)>) at /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:1218
1218 *__result = *__first;

这是在 RedHat 4.1.2-52 上使用 gcc 4.1.2

我的理解是原始指针可以用作 ForwardIterators,但也许不行?有什么建议吗?

最佳答案

该程序在尝试修改字符串文字时具有未定义的行为:

char * test1 = "123a45";

更改为:

char test1[] = "123a45"; // 'test1' is a copy of the string literal.
char * new_end = std::remove_if(test1, test1 + sizeof(test1), is_bad);

参见 http://ideone.com/yzeo4k .

关于c++ - 将 remove_if 与 C 空终止字符串一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802701/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com