gpt4 book ai didi

c++ - 转换指针引用的字符串

转载 作者:行者123 更新时间:2023-12-02 09:53:53 30 4
gpt4 key购买 nike

我正在学习迭代器,并决定通过迭代字符串 vector 并将其转换为小写字母来使用迭代器。这样做的时候,我到了无法弄清楚哪里出问题的地步。这是我一直在使用的代码:

#include <iostream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm>
#include <cctype>

int main()
{
std::vector<std::string> vec = {"AbBBBcCc", "AFFDDsDCc"};

for (std::vector<std::string>::iterator it = vec.begin(); it != vec.end(); ++it)
{
std::transform(*it->begin(), *it->end(), *it->begin(),
[](char c) { return std::tolower(c); });
std::cout << *it << std::endl;
}
return 0;
}

当我第一次试图弄清楚这一点时,有很多错误。我现在得到的唯一错误是:
error: invalid type argument of unary '*' (have 'char')
4298 | *__result = __unary_op(*__first);

我不知道如何解决它。我通过将指针解引用为常规字符串变量并用该变量替换了转换函数中的指针调用来使其工作。我知道这远不是实现此目的的最佳方法,但我只是想知道为什么此代码无法正常工作。

谢谢。

最佳答案

std::transform(*it->begin(), *it->end(), *it->begin(),

此处的 it遍历 vector 中的 std::string,并引用 vector 中的某些字符串。其 ->重载解析为迭代器当前引用的字符串。因此:
it->begin()

调用 std::string::begin(),它返回一个迭代器,该迭代器返回字符串的开头和第一个字符。因此
*it->begin()

给您字符串中的第一个字符, *it->end()当然是未定义的行为。取消引用结尾的迭代器值始终是未定义的行为,因此表达式“ *it->end()”应让您暂停一下,并根据自己的优点给您一些思考。您显然打算这样做:
  std::transform(it->begin(), it->end(), it->begin(),
[](char c) { return std::tolower(c); });

关于c++ - 转换指针引用的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62011058/

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