logo

Jak uzyskać dostęp do elementów wektorowych w C++

Wstęp

Ze względu na dynamiczny rozmiar i prostotę użycia wektory należą do najczęściej używanych struktur danych w C++. Zapewniają elastyczność i szybkie wyszukiwanie elementów, umożliwiając przechowywanie i odzyskiwanie elementów w jednym, ciągłym bloku pamięci. W tym samouczku dokładnie zrozumiesz, jak używać wektorów, studiując kilka sposobów uzyskiwania dostępu do elementów wektorowych w C++.

1. Dostęp do elementów według indeksu

Wykorzystanie ich indeksów jest jedną z najłatwiejszych metod uzyskania dostępu do elementów wektorowych. Do każdego elementu wektora przypisywany jest indeks, zaczynając od 0 dla pierwszego elementu i zwiększając się o 1 dla każdego kolejnego elementu. Użyj operatora indeksu dolnego [] i odpowiedniego indeksu, aby pobrać element o danym indeksie.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; int firstElement = numbers[0]; // Accessing the first element int thirdElement = numbers[2]; // Accessing the third element std::cout << 'First Element: ' << firstElement << std::endl; std::cout << 'Third Element: ' << thirdElement << std::endl; return 0; } 

Wyjście:

 First Element: 10 Third Element: 30 

2. Korzystanie z funkcji członkowskiej at().

Kolejną techniką uzyskiwania dostępu do elementów wektorowych jest użycie funkcji członkowskiej at(). Metoda at() umożliwia sprawdzanie granic, aby upewnić się, że nie uzyskasz dostępu do elementów większych niż wektor. Jeśli podano indeks spoza zakresu, zgłaszany jest wyjątek std::out_of_range.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; int firstElement = numbers.at(0); // Accessing the first element int thirdElement = numbers.at(2); // Accessing the third element std::cout << 'First Element: ' << firstElement << std::endl; std::cout << 'Third Element: ' << thirdElement << std::endl; return 0; } 

Wyjście:

 First Element: 10 Third Element: 30 

3. Elementy przednie i tylne

Ponadto wektory oferują bezpośredni dostęp do pierwszego i ostatniego elementu odpowiednio za pomocą metod składowych front() i rear(). Gdy potrzebujesz po prostu uzyskać dostęp do punktów końcowych wektora, funkcje te są bardzo pomocne.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; int firstElement = numbers.front(); // Accessing the first element int lastElement = numbers.back(); // Accessing the last element std::cout << 'First Element: ' << firstElement << std::endl; std::cout << 'Last Element: ' << lastElement << std::endl; return 0; } 

Wyjście:

 First Element: 10 Last Element: 50 

4. Używanie iteratorów

Iteratory są potężnym narzędziem do nawigacji i uzyskiwania dostępu do elementów w kontenerach udostępnianych przez C++. Iteratory wektorów występują w dwóch wersjach: Begin() i end(). Iterator end() wskazuje jedno miejsce po ostatnim elemencie, podczas gdy iterator Begin() wskazuje element początkowy wektora. Dostęp do elementów wektora można uzyskać iterując po nim za pomocą tych iteratorów.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; // Accessing elements using iterators for (auto it = numbers.begin(); it != numbers.end(); ++it) { int element = *it; // Process the element std::cout << element << ' '; } std::cout << std::endl; return 0; } 

Wyjście:

 10 20 30 40 50 

5. Dostęp do elementów za pomocą pętli for opartej na zakresie

W C++ 11 wprowadzono pętlę for opartą na zakresach, która usprawnia proces iteracji poprzez automatyczne zarządzanie iteratorami. Bez jawnego utrzymywania iteratorów możesz uzyskać dostęp do elementów wektorowych za pomocą tej funkcji.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; // Accessing elements using a range-based for loop for (int element : numbers) { // Process the element std::cout << element << ' '; } std::cout << std::endl; return 0; } 

Wyjście:

 10 20 30 40 50 

6. Dostęp do elementów za pomocą wskaźników

Wektory są zaimplementowane w C++ jako dynamicznie tworzona tablica, a wskaźniki służą do uzyskiwania dostępu do ich elementów. Do uzyskania adresu pamięci pierwszego elementu można użyć funkcji składowej data(), a do uzyskania adresów kolejnych elementów można zastosować arytmetykę wskaźników.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; // Accessing elements using pointers int* ptr = numbers.data(); // Get the pointer to the first element for (size_t i = 0; i <numbers.size(); ++i) { int element="*(ptr" + i); process the std::cout << ' '; } std::endl; return 0; < pre> <p> <strong>Output:</strong> </p> <pre> 10 20 30 40 50 </pre> <p> <strong>7. Checking Vector Size</strong> </p> <p>Verify that the vector is not empty before attempting to access any of its elements. Use the size() member function to determine a vector&apos;s size. Accessing the elements of an empty vector will result in unexpected behavior.</p> <pre> #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; if (!numbers.empty()) { // Access vector elements for (int element : numbers) { std::cout &lt;&lt; element &lt;&lt; &apos; &apos;; } std::cout &lt;&lt; std::endl; } else { std::cout &lt;&lt; &apos;Vector is empty.&apos; &lt;&lt; std::endl; } return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> 10 20 30 40 50 </pre> <p> <strong>8. Modifying Vector Elements</strong> </p> <p>When you have access to vector elements, you may change them in addition to retrieving their values. Using any of the access techniques, you may give vector elements new values.</p> <pre> #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; numbers[2] = 35; // Modifying an element using index numbers.at(3) = 45; // Modifying an element using at() // Modifying the first and last elements numbers.front() = 15; numbers.back() = 55; // Printing the modified vector for (int element : numbers) { std::cout &lt;&lt; element &lt;&lt; &apos; &apos;; } std::cout &lt;&lt; std::endl; return 0; } </pre> <p> <strong>Output:</strong> </p> <pre> 15 20 35 45 55 </pre> <p> <strong>9. Handling Out-of-Range Access</strong> </p> <p>When utilizing indices to access vector elements, it&apos;s crucial to confirm that the index falls within the acceptable range. Accessing items that are larger than the vector will lead to unpredictable behavior. Make careful to carry out the necessary bounds checking if you need to access items based on computations or user input to prevent any mistakes.</p> <pre> #include #include // Function to get user input size_t getUserInput() { size_t index; std::cout &lt;&gt; index; return index; } int main() { std::vector numbers = {10, 20, 30, 40, 50}; size_t index = getUserInput(); if (index <numbers.size()) { int element="numbers[index];" process the std::cout << 'element at index ' ': std::endl; } else handle out-of-range access 'invalid index. out of range.' return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Enter the index: 2 Element at index 2: 30 </pre> <h3>Conclusion</h3> <p>The ability to access vector elements in C++ is essential for working with this flexible data format. Understanding the different approaches-including index-based access, iterators, pointers, and the range-based for loop-will enable you to reliably obtain and modify vector items as needed for your programmer. To prevent probable problems and undefinable behavior, bear in mind to handle bounds checking, care for vector size, and apply prudence.</p> <hr></numbers.size())></pre></numbers.size();>

7. Sprawdzanie rozmiaru wektora

Zanim spróbujesz uzyskać dostęp do któregokolwiek z jego elementów, sprawdź, czy wektor nie jest pusty. Użyj funkcji członkowskiej size(), aby określić rozmiar wektora. Dostęp do elementów pustego wektora spowoduje nieoczekiwane zachowanie.

rozdaj mapę
 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; if (!numbers.empty()) { // Access vector elements for (int element : numbers) { std::cout &lt;&lt; element &lt;&lt; &apos; &apos;; } std::cout &lt;&lt; std::endl; } else { std::cout &lt;&lt; &apos;Vector is empty.&apos; &lt;&lt; std::endl; } return 0; } 

Wyjście:

 10 20 30 40 50 

8. Modyfikowanie elementów wektorowych

Jeśli masz dostęp do elementów wektorowych, możesz je zmieniać oprócz pobierania ich wartości. Korzystając z dowolnej techniki dostępu, możesz nadać elementom wektorowym nowe wartości.

 #include #include int main() { std::vector numbers = {10, 20, 30, 40, 50}; numbers[2] = 35; // Modifying an element using index numbers.at(3) = 45; // Modifying an element using at() // Modifying the first and last elements numbers.front() = 15; numbers.back() = 55; // Printing the modified vector for (int element : numbers) { std::cout &lt;&lt; element &lt;&lt; &apos; &apos;; } std::cout &lt;&lt; std::endl; return 0; } 

Wyjście:

 15 20 35 45 55 

9. Postępowanie w przypadku dostępu poza zasięgiem

Korzystając z indeksów w celu uzyskania dostępu do elementów wektorowych, ważne jest, aby potwierdzić, że indeks mieści się w dopuszczalnym zakresie. Dostęp do elementów większych niż wektor doprowadzi do nieprzewidywalnego zachowania. Uważaj, aby sprawdzić niezbędne granice, jeśli potrzebujesz dostępu do elementów w oparciu o obliczenia lub dane wejściowe użytkownika, aby zapobiec błędom.

 #include #include // Function to get user input size_t getUserInput() { size_t index; std::cout &lt;&gt; index; return index; } int main() { std::vector numbers = {10, 20, 30, 40, 50}; size_t index = getUserInput(); if (index <numbers.size()) { int element="numbers[index];" process the std::cout << \'element at index \' \': std::endl; } else handle out-of-range access \'invalid index. out of range.\' return 0; < pre> <p> <strong>Output:</strong> </p> <pre> Enter the index: 2 Element at index 2: 30 </pre> <h3>Conclusion</h3> <p>The ability to access vector elements in C++ is essential for working with this flexible data format. Understanding the different approaches-including index-based access, iterators, pointers, and the range-based for loop-will enable you to reliably obtain and modify vector items as needed for your programmer. To prevent probable problems and undefinable behavior, bear in mind to handle bounds checking, care for vector size, and apply prudence.</p> <hr></numbers.size())>

Wniosek

Możliwość dostępu do elementów wektorowych w C++ jest niezbędna do pracy z tym elastycznym formatem danych. Zrozumienie różnych podejść – w tym dostępu opartego na indeksach, iteratorów, wskaźników i pętli for opartej na zakresie – umożliwi niezawodne uzyskiwanie i modyfikowanie elementów wektorowych zgodnie z potrzebami programisty. Aby zapobiec prawdopodobnym problemom i niedefiniowalnemu zachowaniu, należy pamiętać o sprawdzaniu granic, dbaniu o rozmiar wektora i zachowaniu ostrożności.