c++ - `=` 分配给新的 std::string 究竟分配了什么?

标签 c++ stdstring

我想编写一个方法来修剪 std::string 的持续和尾随空格。例如,如果方法获得“HELLO WORLD”,它应该返回“HELLO WORLD”。注意,返回字符串之间是一个空格,这很重要。
这是我的方法的签名:

std::string MyHandler::Trim(const std::string& toTrim)
我的方法是将“toTrim”参数复制到非常量拷贝中。
std::string toTrimCopy = toTrim; 
现在我想获得一个非常量迭代器并在 for 循环中删除从开头和结尾的任何空格,而迭代器的值是一个空格。
for (std::string::iterator it = toTrim.begin(); *it == ' '; it++)
{
    toTrimCopy.erase(it);
}

for (std::string::iterator it = toTrim.end();
     *it == ' ';
     it--)
{
    toTrimCopy.erase(it);
}
这会导致编译器错误:

StringHandling.C:60:49: error: conversion from ‘std::basic_string<char>::const_iterator {aka __gnu_cxx::__normal_iterator<const char*, std::basic_string<char> >}’ to non-scalar type ‘std::basic_string<char>::iterator {aka __gnu_cxx::__normal_iterator<char*, std::basic_string<char> >}’ requested


我来自 Java,现在学习 C++ 3 周。所以不要评判我。我怀疑 =赋值将常量 char 指针分配给我的新字符串,因此我的拷贝是隐含的常量值。但我不完全知道。
顺便说一句,这种方法也会引发异常:
    std::string toTrimCopy = "";
    std::strcpy(toTrimCopy, toTrim);
他说,他不能将字符串转换为 char 指针。

最佳答案

toTrim 传递迭代器是未定义的行为到 toTrimCopy 的方法,所以你很幸运类型不匹配捕获了它。std::string::begin有两个重载:

 std::string::iterator std::string::begin();
 std::string::const_iterator std::string::begin() const;
const字符串的 ness 参与重载决议。您不能初始化 iterator来自 const_iterator ,因为这将允许您通过该迭代器修改基础对象。
我会将您的功能更改为
namespace MyHandlerNS { // optional, could be in global namespace
    std::string Trim(std::string toTrim) {
        for (auto it = toTrim.begin(); it != toTrim.end() && *it == ' ';) {
            it = toTrim.erase(it);
        }

        for (auto it = toTrim.rbegin(); it != toTrim.rend() && *it == ' ';) {
            it = toTrim.erase(it.base());
        }

        return toTrim;
    }
}
或者用标准算法完全摆脱循环
#include <algorithm>

namespace MyHandlerNS { // optional, could be in global namespace
    std::string Trim(std::string toTrim) {
        auto isSpace = [](char c){ return c == ' '; };

        auto it = std::find_if_not(toTrim.begin(), toTrim.end(), isSpace);
        toTrim.erase(toTrim.begin(), it);

        it = std::find_if_not(toTrim.rbegin(), toTrim.rend(), isSpace).base();
        toTrim.erase(it, toTrim.end());

        return toTrim;
    }
}

关于c++ - `=` 分配给新的 std::string 究竟分配了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64459521/

相关文章:

c++ - 我如何迭代集合中的替代元素(或进行特定大小的跳跃)?

c++ - 当内存空间被删除时,指针的值保持不变还是被改变?对象内容是否会改变?

C++:如何将 fprintf 结果作为 std::string 不带 sprintf

c# - 我们如何在 C# 中从 C++ DLL 获取所有方法?

c++ - 我将如何着手将物理学应用于带有子弹的玩家?

c++ - 覆盖 std::string 空终止符合法吗?

c++ - 警告:支持指针的对象将在 std::pair 的完整表达式结束时销毁

c++ - 我的函数操作 std::string 产生了意想不到的结果

c++ - 将长度为 0 的字符串 ('0' ) 传递给需要 char* 的 STL 函数

c++ - 如何声明一个 std::map 以枚举为键,以不同签名为值的函数?