Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CPlusPlusNotesForProfessionals.pdf
Скачиваний:
47
Добавлен:
20.05.2023
Размер:
5.11 Mб
Скачать

Section 49.15: Find max and min Element and Respective Index in a Vector

To find the largest or smallest element stored in a vector, you can use the methods std::max_element and std::min_element, respectively. These methods are defined in <algorithm> header. If several elements are equivalent to the greatest (smallest) element, the methods return the iterator to the first such element. Return v.end() for empty vectors.

std::vector<int> v = {5, 2, 8, 10, 9};

int maxElementIndex = std::max_element(v.begin(),v.end()) - v.begin(); int maxElement = *std::max_element(v.begin(), v.end());

int minElementIndex = std::min_element(v.begin(),v.end()) - v.begin(); int minElement = *std::min_element(v.begin(), v.end());

std::cout << "maxElementIndex:" << maxElementIndex << ", maxElement:" << maxElement << '\n'; std::cout << "minElementIndex:" << minElementIndex << ", minElement:" << minElement << '\n';

Output:

maxElementIndex:3, maxElement:10 minElementIndex:1, minElement:2

Version ≥ C++11

The minimum and maximum element in a vector can be retrieved at the same time by using the method std::minmax_element, which is also defined in <algorithm> header:

std::vector<int> v = {5, 2, 8, 10, 9};

auto minmax = std::minmax_element(v.begin(), v.end());

std::cout << "minimum element: " << *minmax.first << '\n'; std::cout << "maximum element: " << *minmax.second << '\n';

Output:

minimum element: 2 maximum element: 10

Section 49.16: Converting an array to std::vector

An array can easily be converted into a std::vector by using std::begin and std::end:

Version ≥ C++11

int values[5] = { 1, 2, 3, 4, 5 }; // source array

std::vector<int> v(std::begin(values), std::end(values)); // copy array to new vector

for(auto &x: v)

std::cout << x << " "; std::cout << std::endl;

GoalKicker.com – C++ Notes for Professionals

284

1 2 3 4 5

int main(int argc, char* argv[]) {

// convert main arguments into a vector of strings. std::vector<std::string> args(argv, argv + argc);

}

A C++11 initializer_list<> can also be used to initialize the vector at once

initializer_list<int> arr = { 1,2,3,4,5 }; vector<int> vec1 {arr};

for (auto & i : vec1) cout << i << endl;

Section 49.17: Functions Returning Large Vectors

Version ≥ C++11

In C++11, compilers are required to implicitly move from a local variable that is being returned. Moreover, most compilers can perform copy elision in many cases and elide the move altogether. As a result of this, returning large objects that can be moved cheaply no longer requires special handling:

#include <vector> #include <iostream>

//If the compiler is unable to perform named return value optimization (NRVO)

//and elide the move altogether, it is required to move from v into the return value. std::vector<int> fillVector(int a, int b) {

std::vector<int> v; v.reserve(b-a+1);

for (int i = a; i <= b; i++) { v.push_back(i);

}

return v; // implicit move

}

int main() { // declare and fill vector std::vector<int> vec = fillVector(1, 10);

// print vector

for (auto value : vec)

std::cout << value << " "; // this will print "1 2 3 4 5 6 7 8 9 10 "

std::cout << std::endl;

return 0;

}

Version < C++11

Before C++11, copy elision was already allowed and implemented by most compilers. However, due to the absence of move semantics, in legacy code or code that has to be compiled with older compiler versions which don't implement this optimization, you can find vectors being passed as output arguments to prevent the unneeded copy:

#include <vector> #include <iostream>

GoalKicker.com – C++ Notes for Professionals

285

// passing a std::vector by reference

void fillVectorFrom_By_Ref(int a, int b, std::vector<int> &v) { assert(v.empty());

v.reserve(b-a+1);

for (int i = a; i <= b; i++) { v.push_back(i);

}

}

int main() {// declare vector std::vector<int> vec;

// fill vector fillVectorFrom_By_Ref(1, 10, vec); // print vector

for (std::vector<int>::const_iterator it = vec.begin(); it != vec.end(); ++it) std::cout << *it << " "; // this will print "1 2 3 4 5 6 7 8 9 10 "

std::cout << std::endl; return 0;

}

GoalKicker.com – C++ Notes for Professionals

286