1

我现在正在与stringin一起工作vector。我让自己陷入了死胡同。我已经使用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元素并将单词更改为上部,但它对我不起作用,它只是示例
我尝试了很多方法来访问vector元素,但是当尝试使用string成员函数toupper()时,vector我变得一团糟代码和逻辑错误!
谢谢你的时间 。对不起,我在拼写单词时犯了错误

4

3 回答 3

4

尝试这个:

for (auto& word: words)
  for (auto& letter: word)
    letter = std::toupper(letter);
于 2013-06-09T00:16:37.247 回答
2

这可以通过使用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;
}

这是一个演示。

于 2013-06-08T23:57:23.660 回答
0

您可以在第一个 for 循环中执行此操作:

string w = words.at(i);
std::transform(w.begin(), w.end(), w.begin(), ::toupper);
于 2013-06-08T23:49:08.313 回答