LoginSignup
1

More than 5 years have passed since last update.

C++: ベクトルの要素へのアクセス

Last updated at Posted at 2016-10-02

C++で、ベクトルの要素へアクセスする。

  • インデックスを指定:x[i]
  • イテレータを利用:*(it+i)
  • ベクトルへのポインタから:*(p)[i], *(p->begin()+i)
#include <iostream>
#include <vector>

int main(int argc, char* argv[])
{
  std::vector<int> x;
  x.push_back(9); x.push_back(5);

  // access elements by index
  std::cout << x[0] << " ";
  std::cout << x[1] << "\n";    

  // access elements using iterator
  std::vector<int>::iterator it = x.begin(); 
  std::cout << *it << " ";
  std::cout << *(it+1) << "\n";    

  // access elements from pointer
  std::vector<int> *p;
  p = &x;
  std::cout << *(p->begin()) << " ";
  std::cout << *(p->begin() + 1) << "\n";

  std::cout << (*p)[0] << " ";
  std::cout << (*p)[1] << "\n";

  return 0;
}

実行結果

9 5
9 5
9 5
9 5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1