C++
c++에서 vector에 접근하는 4가지 방법
GunwooYun
2024. 1. 21. 11:00
There are 4 ways to access the elements of vector in C++. (from chatgpt)
- Using Subscript Operator ([]): You can access vector elements using the subscript operator. Remember that vector indices start from 0.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers[i] << " ";
}
return 0;
}
- Using Iterator: You can use iterators to traverse through the elements of a vector. This is particularly useful when you want to work with elements in a generic way.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
- Using Range-Based For Loop (C++11 and later): C++11 introduced range-based for loops, providing a concise way to iterate through elements.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (const auto& num : numbers) {
std::cout << num << " ";
}
return 0;
}
- Using at() Member Function: The at() member function allows you to access elements with bounds checking. It throws an out_of_range exception if the index is out of bounds.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (size_t i = 0; i < numbers.size(); ++i) {
std::cout << numbers.at(i) << " ";
}
return 0;
}