为什么我的函数接受“std::string”来排序不更改它?

Why doesn't my function that accepts an `std::string` to sort change it?

提问人:MikeK 提问时间:6/10/2020 最后编辑:asmmoMikeK 更新时间:6/11/2020 访问量:76

问:

我有一个项目,我想问一些事情。如何使用 ?我从我找到的一个网站上尝试过这个,但它不适用于 cin。代码如下:cin<<word;

void descOrder(string s) 
{ 
    sort(s.begin(), s.end(), greater<char>()); 
} 

int main() 
{ 
    string s = "geeksforgeeks"; 
    descOrder(s); // function call 
    return 0; 
} 

为了更清楚,我想这样做

  • 输入:geek for geeks
  • 输出ssrokkggfeeee

另外,我如何使用字母表替换字符串中的字母,例如,Hello I want to be like this H to be I, e to be f, l to be m, o to be p,如果一个单词包含字母 z,我想用字母 a 替换。

最后一个问题,我想先从字符串中打印,根据元音,然后从元音开始

C++ 字符串 排序 按引用传递

评论

3赞 Abhishek Choudhary 6/10/2020
请写下描述性标题,以便其他人可以搜索

答:

2赞 asmmo 6/10/2020 #1

你正在传递你的值,因此从中获取一个副本,然后对它进行排序,你什么也没得到。std::stringdesOrder()

通过引用传递您的内容,以便能够更改它,而不是从中复制它。std::string

#include <string>
#include <iostream>
#include <algorithm>

void descOrder(std::string & s)
{
    std::sort(s.begin(), s.end(), std::greater<char>());
}

int main()
{
    std::string s = "geeksforgeeks";
    descOrder(s); // function call
    std::cout << s;
    return 0;
}

请为每篇帖子发布一个问题,看看为什么“使用命名空间 std;”被认为是不好的做法?

评论

0赞 Wolfgang 6/10/2020
另一种解决方案是从 descOrder 返回排序后的字符串(按值): std::string descOrder(std::string s) { std::sort(s.begin(), s.end(), std::greater<char>()); return s; } ..in main: int main() { auto s = descOrder(“geeksforgeeks”); std::cout << s; return 0; } - 这样你就得到了一个干净返回的函数。
0赞 asmmo 6/10/2020
@Wolfgang我想纠正一些被 OP 误解的东西,不想改变 OP 的结构。
1赞 Wolfgang 6/10/2020
我理解并欢迎这一点,这就是为什么我只作为评论而不是替代答案插入我的评论。尽管如此,我希望向OP表明还有其他合理的方法。
1赞 Rohan Bari 6/11/2020 #2

有两种方法适用:

1. 通过引用传递值:

当您通过引用传递变量时,它会操作原始变量的值:

#include <iostream>
#include <algorithm>

void descOrder(std::string & s) // just use an '&' sign here
{ 
    sort(s.begin(), s.end(), std::greater<char>()); 
} 

int main() 
{ 
    std::string s = "geeksforgeeks";

    descOrder(s); // function call

    std::cout << s << std::endl;

    return 0; 
}

2. 返回值而不是通过引用传递:

如果您不想更改原始值,但想存储在另一个变量中或直接打印它,您可以执行以下操作:

#include <iostream>
#include <algorithm>

std::string descOrder(std::string s) 
{ 
    sort(s.begin(), s.end(), std::greater<char>());
    return s;
} 

int main() 
{ 
    std::string s = "geeksforgeeks";

    std::string changedS = descOrder(s); // function call AND assigning to another variable

    std::cout << changedS << std::endl;

    // alternatively (uncomment)...
    // std::cout << descOrder(s) << std::endl; // if you just want to print

    return 0; 
}