a.cpp: In instantiation of ‘void print(T) [with T = int]’: a.cpp:23:11: required from here a.cpp:18:19: error: request for member ‘c_str’ in ‘obj’, which is of non-class type ‘int’ std::cout << obj.c_str() << ", length: " << obj.length() << "\n"; ~~~~^~~~~ a.cpp:18:51: error: request for member ‘length’ in ‘obj’, which is of non-class type ‘int’ std::cout << obj.c_str() << ", length: " << obj.length() << "\n";
int* findArray(int *arr, int size, int v) { for (int i = 0; i < size; i++) if (arr[i] == v) return arr + i; returnNULL; } int *p = findArray(arr, size, v); if (p) *p = anotherValue;
std::optional<int&> findArray(std::vector<int> &arr, int v) { for (size_t i = 0; i < arr.size(); i++) if (arr[i] == v) return arr[i]; return {}; } std::option<int&> p = findArray(arr, v); if (p) *p = anotherValue;
template <typename T> intcalc(const T& v) { usingnamespace ranges; return count_if(v | view::sliding(2), [](constauto &v) { auto begin = ranges::begin(v); auto front = *begin++; auto back = *begin++; return front < back; }); }
第一種很直覺,不過跟C++11提倡的Range based loop算是一種退化 而第二種出現了4個array,一不小心還會有打錯字的風險 天才作者提出了第三種方式
1 2 3 4 5
for (auto& item : iter::eraser(array)) { if (*item == value) // Access item via deref item.mark_for_erase(); // Item is marked for deletion, but is still valid until end of loop iteration }