How do I get a pointer from a class c ++ vector? For example I have a vector a; , how do I get a pointer to just one vector element?
How do I get a pointer from a class c ++ vector? For example I have a vector a; , how do I get a pointer to just one vector element?
From c ++ 11 you can use the data function. It returns the address of the array used to store the vector elements.
Note that if the vector has no elements, data()
may or may not return nullptr
#include <iostream>
#include <vector>
int main() {
std::vector<int> cheio{1, 2, 3};
std::vector<int> vazio;
cheio.clear();
std::cout << std::boolalpha << "vazio.data() == nullptr? "
<< (vazio.data() == nullptr) << "\n"
<< "cheio.data() == nullptr? "
<< (cheio.data() == nullptr) << "\n";
}
vazio.data() == nullptr? true
cheio.data() == nullptr? false