traversing a vector in c++ code example
Example 1: c++ iterate through vectgor
std::vector<int> vec_of_ints(100);
for (int i = 0; i < vec_of_ints.size(); i++){
std::cout << vec_of_ints.at(i) << " ";
}
std::cout << std::endl;
Example 2: sort vector struct c++
struct data{
string word;
int number;
};
bool my_cmp(const data& a, const data& b)
{
return a.number < b.number;
}
std::sort(A.begin(), A.end(), my_cmp);
Example 3: declare vectors c++
vector<int> vec;
vector<int> vec(4);
vector<int> vec(4, 42);
vector<int> vec(4, 42);
vector<int> vec2(vec);
Example 4: sorting vector of structs c++
struct data{
string word;
int number;
};
bool my_cmp(const data& a, const data& b)
{
return a.number() < b.number();
}
std::sort(A.begin(), A.end(), my_cmp);