C++ std::vector 总结笔记

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

  1. v.empty(): return true if v is empty
  2. v.size: return the number of elements in v
  3. v.push_back(t): add an element to v.
  4. 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

你可能感兴趣的:(C++ std::vector 总结笔记)