In C++, vectors are collections of items. Each item can be accessed using an index, which represents its position in the vector. Indexing starts from 0 for the first item.
#include <iostream> #include <vector> int main() { std::vector<double> prices = {3.99, 12.99, 2.49}; std::cout << prices[0] << "\n"; // Prints: 3.99 std::cout << prices[2] << "\n"; // Prints: 2.49 return 0; }
Vectors in C++ are used to store a list of items. You can create a vector, set its items by index, and access them as needed.
#include <iostream> #include <vector> int main() { std::vector<int> scores(3); scores[0] = 90; scores[1] = 86; scores[2] = 98; std::cout << scores[0] << "\n"; // Prints: 90 return 0; }
Vectors can dynamically grow or shrink. Use `.push_back()` to add an item and `.pop_back()` to remove the last item.
#include <iostream> #include <vector> int main() { std::vector<std::string> items; items.push_back("Laptop"); items.push_back("Headphones"); items.pop_back(); std::cout << items.size() << "\n"; // Prints: 1 return 0; }
To use vectors, you need to include the vector library at the beginning of your program with `#include <vector> `.
#include <iostream> #include <vector> int main() { std::vector<std::string> names = {"Alice", "Bob", "Charlie"}; std::cout << names.size() << "\n"; // Prints: 3 return 0; }
You can use the `.size()` function to find out how many items are in a vector. It returns the number of elements currently in the vector.
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; std::cout << numbers.size() << "\n"; // Prints: 5 return 0; }
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!