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使用しようとすると面倒ですコードと論理的な間違い! 御時間ありがとうございます 。単語のスペルを間違えてごめんなさいstringtoupper()vector

4

3 に答える 3

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 に答える