C++std::vectorまとめノート

1675 ワード

Initialization
#include
#include

using namespace std;
int main()
{
    vector ivec(10, -1);
    vector ivec2(ivec);
    for (auto x : ivec2) {cout << x << endl;}

    vector jvec(10); //initialized as 0s;
    for (auto x: jvec)
        cout << x << endl;

    vector zvec{1,2,3};
    vector avec={1,2,3}; //zvec and avec are equivalent
    for (int i=0; i

Methods
  • v.empty() : return true if v is empty
  • v.size : return the number of elements in v
  • v.push_back(t) : add an element to v.
  • v1==v2 : return true if number and values are equal
  • int main()
    {
        vector avec{1,2,3};
        vector bvec{1,2,3};
        cout << (avec==bvec) << endl;
        cout << (&avec==&bvec) << endl;
    
        return 0;
    }
    
    1
    0
    [Finished in 0.9s]

    Iterator
    int main()
    {
        string s("hello");
        if (s.begin()!=s.end())
        {
            auto it = s.begin();
            *it = toupper(*it);
        }
        cout << s << endl;
        for (auto it = s.begin(); it !=s.end() && !isspace(*it); ++it)
        {
            *it = toupper(*it);
        }
        cout << s << endl;
        return 0;
    
    }
    
    Hello
    HELLO
    [Finished in 0.8s]
    vector::iterator it vector::const_iterator it2 : it2 can read but not write