更改vector中的字符串元素值

Change string element value in vector

本文关键字:元素 字符串 vector 更改      更新时间:2023-10-16

我现在正在vector中与string合作。我把自己带进了死胡同。我操纵vector<int>元素,并了解如何与他们一起工作!我知道如何使用string !但是我无法通过我需要改变向量中的字符串元素值的部分。我的意思是我不知道在loop中"做点什么"该怎么办。所以简而言之,我把任务交给了我现在工作的人。

cin中读取一系列单词,并将值存储在vector中。在读取所有单词后,处理vector并将每个单词更改为大写

到目前为止我得到了什么

int main ()  
{
    vector<string> words;    //Container for all input word
    string inp;              //inp variable will process all input 
    while (cin>>inp)         //read
       words.push_back(inp); //Storing words 
    //Processing vector to make all word Uppercase
    for (int i = 0; i <words.size(); ++i)
     //do something
         words[i]=toupper(i);
    for (auto &e : words)    //for each element in vector 
     //do something
     cout<<e;
    keep_window_open("~");
    return 0;
}  

第一个for语句不正确,我尝试访问vector元素并将单词更改为upper,但它不适合我,它只是示例
我尝试了很多方法来访问vector元素,但当试图使用string成员函数toupper()vector我得到混乱的代码和逻辑错误!
谢谢你的宝贵时间。很抱歉我在拼写单词时犯了错误

试试这个:

for (auto& word: words)
  for (auto& letter: word)
    letter = std::toupper(letter);

这可以通过使用std::transform标准算法来遍历单词的字符来修复。您也可以使用std::for_each来代替手动循环。

#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>
#include <vector>
int main()  
{
    std::vector<std::string> words;
    std::string inp;
    while (std::cin >> inp)
       words.push_back(inp);
    std::for_each(words.begin(), words.end(), [] (std::string& word)
    {
        std::transform(
            word.begin(),
            word.end(), 
            word.begin(), (int (&)(int)) std::toupper
        );
    })
    for (auto &e : words)
        std::cout << e << std::endl;
}

这里是一个演示

可以在第一个for循环中这样做:

string w = words.at(i);
std::transform(w.begin(), w.end(), w.begin(), ::toupper);