在C++中使用字符串::擦除时出错

Error using string::erase in C++

本文关键字:擦除 出错 字符串 C++      更新时间:2023-10-16

我在编译C++程序时遇到错误。下面是我的代码!

#include <pthread.h>
#include "Path.h"
#include "Maze.h"
#include "SubmitMazeSoln.h"
#include "Assignm3_Utils.h"
#include "Assignm3.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
srand(time(NULL));
string random = "0123";
for (int i = 0; i < 4; i++)
{
    int x = (rand () % random.size());
    char y = random[x];
    random.erase(remove(random.begin(), random.end() + y), random.end());
    int temp;
        if (threadData.threadIDArrayIndex == 0)
        {
            temp = i;
        }
        else
        {
            temp = y - '0';
        }
}

编译程序时的错误。

myprog.cpp: In function ‘void* exploreMaze(void*)’:
myprog.cpp:108:56: error: cannot convert ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ to ‘const char*’ for argument ‘1’ to ‘int remove(const char*)’
random.erase(remove(random.begin(), random.end() + y), random.end());

对不起,伙计们的帮助深表感谢!谢谢!

正如DaveB所说,

remove(random.begin(), random.end() + y)

应该是

remove(random.begin(), random.end(), y)

错误消息令人困惑,因为random.end() + y是一个有效的表达式,尽管它生成的迭代器远离容器的末尾。因此,编译器看到对具有两个参数的函数remove的调用,并尝试理解它。编译器看到一个带有签名remove(const char*)的函数,并猜测这就是你的意思,然后抱怨它无法将第一个参数转换为类型 const char*

如果您使用正确的C++标准库名称(如 std::remove),则不会发生这种混淆。 using namespace std;又来了!