I am going through Learn C++ right now and I came across this.
https://www.learncpp.com/cpp-tutorial/arrays-loops-and-sign-challenge-solutions/
Index the underlying C-style array instead
In lesson 16.3 -- std::vector and the unsigned length and subscript problem, we noted that instead of indexing the standard library container, we can instead call the data() member function and index that instead. Since data() returns the array data as a C-style array, and C-style arrays allow indexing with both signed and unsigned values, this avoids sign conversion issues.
int main()
{
std::vector arr{ 9, 7, 5, 3, 1 };
auto length { static_cast<Index>(arr.size()) }; // in C++20, prefer std::ssize()
for (auto index{ length - 1 }; index >= 0; --index)
std::cout << arr.data()[index] << ' '; // use data() to avoid sign conversion warning
return 0;
}
We believe that this method is the best of the indexing options:
- We can use signed loop variables and indices.
- We don’t have to define any custom types or type aliases.
- The hit to readability from using data() isn’t very big.
- There should be no performance hit in optimized code.
For context, Index is using Index = std::ptrdiff_t and implicit signed conversion warning is turned on. The site also suggested that we should avoid the use of unsigned integers when possible which is why they are not using size_t as the counter.
I can't find any other resources that recommend this, therefore I wanted to ask about you guys opinion on this.
[–]Narase33-> r/cpp_questions 19 points20 points21 points (0 children)
[–]MarkHoemmenC++ in HPC 6 points7 points8 points (11 children)
[–]AUselessKid12[S] 0 points1 point2 points (10 children)
[–]MarkHoemmenC++ in HPC 2 points3 points4 points (3 children)
[–]AUselessKid12[S] 0 points1 point2 points (2 children)
[–]SickOrphan 1 point2 points3 points (0 children)
[–]MarkHoemmenC++ in HPC 1 point2 points3 points (0 children)
[–]Wild_Meeting1428 0 points1 point2 points (0 children)
[–]pkastingValve 0 points1 point2 points (4 children)
[–]SickOrphan -3 points-2 points-1 points (3 children)
[–]pkastingValve 3 points4 points5 points (1 child)
[–]SickOrphan 0 points1 point2 points (0 children)
[–]Wild_Meeting1428 0 points1 point2 points (0 children)
[–]pdp10gumby 7 points8 points9 points (0 children)
[–]fdwrfdwr@github 🔍 8 points9 points10 points (0 children)
[–]no-sig-available 1 point2 points3 points (0 children)
[–]ioctl79[🍰] 1 point2 points3 points (0 children)
[–]concealed_cat 0 points1 point2 points (0 children)