c++ primer 標準庫類型 vector

ps:本文內的程序均爲c++ 11 標準,codeblocks13.12 

歡迎大家評論拍磚,消滅0回覆啊,求交流,求回覆,求贊,

http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read?page=1&tab=votes#tab-top

據說要成爲牛逼的coder要看這些,感覺。。。

在用while循環輸入時,按下CTRL+Z回車即可停止輸入,新技能get


vector是一個類模板,常被稱爲容器(container)


3.17

#include<cctype>
using namespace std;

int main()
{
    string in;
    vector<string> vstr;
    while(cin>>in && in!= "#")
    {
        vstr.push_back(in);
    }
    if(!vstr.empty())
    {
        string str;
            for(auto &c: vstr)
            {

               for(auto &ch:c)      //在單詞裏面單個字符大寫
               {
                    ch = toupper(ch);
               }
                    cout<< c<<endl;
            }
    }

    return 0;
}

3.19

#include <iostream>
#include<vector>
#include<string>
#include<cctype>
using namespace std;

int main()
{
   vector<int> ivec(10,42);
   vector<int> ivec2{42,42,42,42,42,42,42,42,42,42};
   vector<int> ivec3(10);
   for(auto &c: ivec3)
   {
       c=42;
   }
  // ivec[0] = 42;

    return 0;
}
當然第一種好,簡單粗暴

3.20

#include <iostream>
#include<vector>
#include<string>
#include<cctype>
using namespace std;

int main()
{
   vector<int>  v1;
   int num;
   while(cin>>num && num!=0)
   {
       v1.push_back(num);
   }
   if(!v1.empty())
   {
       for(decltype(v1.size()) i =0,j = v1.size()-1;i <= j;i++,j--)
        {
                cout<<v1[i] +v1[j]<< endl;
        }
   }

    return 0;
}

3.22  被註釋掉的是老版本的個人覺得沒有for好用

這個程序調試的時候廢了好大勁,現在看來是當時腦殘了,果斷放了兩天來寫,一會兒就好了,哈哈哈哈

#include<iostream>
#include<vector>
#include<string>
#include<cctype>
using namespace std;

int main()
{
    vector<string> vstr;
    string str;
    cout<< "enter text(CTRL +Z to end):"<< endl;
    while(getline(cin,str))
    {
        vstr.push_back(str);
    }
    if(vstr.size()  ==0)
    {
        cout << "no strings there"<< endl;
        return -1;
    }
    cout <<"##########"<<"then topper"<<endl;
    for(auto it= vstr.begin();it != vstr.end() && !it->empty(); ++it)
    {

        /*for(string::size_type index= 0;index != (*it).size();
        ++index)
        {
            (*it)[index] = toupper((*it)[index]);
        }*/
        for(auto  &itor: (*it))  //(*it)返回第一個string的引用,所以我用了引用的引用
        {
            itor = toupper(itor);
        }

    }
    for(auto ch:vstr)
    {
        cout<< ch<<endl;
    }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章