text
stringlengths
1
2.12k
source
dict
java, beginner, game, console import java.util.Optional; import java.util.Random; import java.util.Scanner; public class Game { public record Hit( boolean blocked, int attack_points ) { @Override public String toString() { if (attack_points == 0) return "no damage"; if (attack_points == 1) return "1 point of damage"; return "%d points of damage".formatted(attack_points); } } public static class Character { private int health; private int defense; private final int strength; public final String name; public Character(String name, Random rand) { health = rand.nextInt(1, 100); defense = rand.nextInt(1, 100); strength = rand.nextInt(1, 100); this.name = name; } public boolean isAlive() { return health > 0; } public Hit receiveHit(Character attacker) { int attack_points = Integer.max(0, attacker.strength - defense); boolean blocked = attack_points == 0; if (blocked) defense -= (defense % attacker.strength) + 1; health = Integer.max(0, health - attack_points); return new Hit(blocked, attack_points); } private void printStats() { System.out.printf("%s's Stats:%n", name); System.out.println("---------------"); final String fmt = "%-10s %-2d%n"; System.out.printf(fmt, "Health:", health); System.out.printf(fmt, "Defense:", defense); System.out.printf(fmt, "Strength:", strength); System.out.println(); } @Override public String toString() { return name; } }
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console @Override public String toString() { return name; } } private final Random rand = new Random(); private final Scanner scanner = new Scanner(System.in); private final Character hero; private final Character enemy = new Character("Spock", rand); public Game() { System.out.println("Welcome to the arena!"); System.out.print("Enter your hero's name: "); hero = new Character(scanner.nextLine(), rand); System.out.printf("Avast, %s! Go forth!%n", hero); } public void clash() { System.out.printf("%s takes a cheap shot!%n", enemy); System.out.println("(Crowd gasps)"); System.out.printf("But %s blocks it in the nick of time!%n", hero); System.out.println("(Crowd cheers)"); } public Optional<Character> rollInitiative() { int hero_initiative = rand.nextInt(1, 7), enemy_initiative = rand.nextInt(1, 7); if (hero_initiative > enemy_initiative) return Optional.of(hero); if (hero_initiative < enemy_initiative) return Optional.of(enemy); return Optional.empty(); // tie ("cheap shot") } public void attack(Character attacker, Character defender) { Hit hit = defender.receiveHit(attacker); if (hit.blocked) { System.out.printf("%s blocks %s's attack and takes %s!%n", defender, attacker, hit); System.out.println("(Crowd cheers)"); } else { System.out.printf("%s strikes %s for %s!%n", attacker, defender, hit); System.out.println("(Crowd boos)"); } }
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console public void doBattle() { Optional<Character> goesFirst = rollInitiative(); if (goesFirst.isPresent()) { Character attacker = goesFirst.get(); System.out.printf("%s takes initiative!%n", attacker); Character defender = hero == attacker? enemy: hero; attack(attacker, defender); } else { clash(); // tie ("cheap shot") } } public void run() { do { System.out.println(); hero.printStats(); enemy.printStats(); if (!hero.isAlive()) { System.out.printf("%s defeats %s!%n", enemy, hero); System.out.println("(Crowd boos aggressively)"); System.out.println("Someone from the crowd yells \"YOU SUCK!\""); break; } if (!enemy.isAlive()) { System.out.printf("%s utterly smites %s!%n", hero, enemy); System.out.println("(Crowd ROARS)"); break; } } while (doRound()); } private boolean doRound() { while (true) { System.out.print("Enter option (1 to battle, 2 to escape)! "); switch (scanner.nextLine()) { case "1": doBattle(); return true; case "2": System.out.println("YOU COWARD!"); return false; default: System.err.println("Invalid option"); } } } public static void main(String[] args) { new Game().run(); } } Output Welcome to the arena! Enter your hero's name: Kirk Avast, Kirk! Go forth! Kirk's Stats: --------------- Health: 68 Defense: 59 Strength: 50 Spock's Stats: --------------- Health: 56 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Spock takes a cheap shot! (Crowd gasps) But Kirk blocks it in the nick of time! (Crowd cheers)
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console Kirk's Stats: --------------- Health: 68 Defense: 59 Strength: 50 Spock's Stats: --------------- Health: 56 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Kirk takes initiative! Kirk strikes Spock for 47 points of damage! (Crowd boos) Kirk's Stats: --------------- Health: 68 Defense: 59 Strength: 50 Spock's Stats: --------------- Health: 9 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Spock takes a cheap shot! (Crowd gasps) But Kirk blocks it in the nick of time! (Crowd cheers) Kirk's Stats: --------------- Health: 68 Defense: 59 Strength: 50 Spock's Stats: --------------- Health: 9 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Spock takes a cheap shot! (Crowd gasps) But Kirk blocks it in the nick of time! (Crowd cheers) Kirk's Stats: --------------- Health: 68 Defense: 59 Strength: 50 Spock's Stats: --------------- Health: 9 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Spock takes initiative! Kirk blocks Spock's attack and takes no damage! (Crowd cheers) Kirk's Stats: --------------- Health: 68 Defense: 48 Strength: 50 Spock's Stats: --------------- Health: 9 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Spock takes a cheap shot! (Crowd gasps) But Kirk blocks it in the nick of time! (Crowd cheers) Kirk's Stats: --------------- Health: 68 Defense: 48 Strength: 50 Spock's Stats: --------------- Health: 9 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Spock takes initiative! Spock strikes Kirk for 1 point of damage! (Crowd boos) Kirk's Stats: --------------- Health: 67 Defense: 48 Strength: 50 Spock's Stats: --------------- Health: 9 Defense: 3 Strength: 49 Enter option (1 to battle, 2 to escape)! 1 Kirk takes initiative! Kirk strikes Spock for 47 points of damage! (Crowd boos)
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
java, beginner, game, console Kirk's Stats: --------------- Health: 67 Defense: 48 Strength: 50 Spock's Stats: --------------- Health: 0 Defense: 3 Strength: 49 Kirk utterly smites Spock! (Crowd ROARS) Stats tables A simple way to condense your stats to a table-like format could look like public static void printStats(Character... chars) { System.out.print(" ".repeat(9)); for (Character col: chars) System.out.printf("%8s ", col); System.out.println(); System.out.print("-".repeat(8)); for (Character col: chars) System.out.print("-".repeat(9)); System.out.println(); System.out.printf("%8s ", "Health"); for (Character col: chars) System.out.printf("%8d ", col.health); System.out.println(); System.out.printf("%8s ", "Defense"); for (Character col: chars) System.out.printf("%8d ", col.defense); System.out.println(); System.out.printf("%8s ", "Strength"); for (Character col: chars) System.out.printf("%8d ", col.strength); System.out.printf("%n%n"); } called like Character.printStats(hero, enemy); with output Kirk Spock -------------------------- Health 78 42 Defense 99 5 Strength 93 97
{ "domain": "codereview.stackexchange", "id": 45425, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, beginner, game, console", "url": null }
c# Title: Should I automatically swap matrix dimensions if the passed matrices are formatted incorrectly?
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# Question: I'm working on making a matrix math object that's as generic as possible. I currently have done multiplication. I've run into a decision I have to make, but first, here's the code. namespace MatrixMath { /// <summary> /// Matrix is a class designed to do math on matrices for you. /// Matrix methods assume that the matrices are formatted as [rows, columns] or [rows][columns]. /// </summary> public static class Matrix { /// <summary> /// Multiplies two matrices together. Assumes formatting is [rows, columns]. Will automatically /// correct this when wrong, except when both matrices have the same number of rows and columns. /// </summary> /// <example> /// If the return value is the answer you expect from multiplying <paramref name="secondMatrix"/> by <paramref name="firstMatrix"/> /// instead of what you intended, this typically means you've formatted your matrices as /// [columns, rows]. The following code example should fix your issue. /// /// Matrix.Multiply(Matrix.SwapDimensions(secondMatrix), Matrix.SwapDimensions(firstMatrix)); /// </example> /// <typeparam name="T">The datatype the matrices are. If it's a non numeric datatype, an <see cref="ArgumentException"/> will be thrown.</typeparam> /// <param name="firstMatrix">The first matrix to multiply.</param> /// <param name="secondMatrix">The second matrix to multiply.</param> /// <returns>The product of the two matrices.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="InvalidOperationException"></exception> public static T[,] Multiply<T>(T[,] firstMatrix, T[,] secondMatrix) { if (firstMatrix is null) throw new ArgumentNullException(nameof(firstMatrix)); if (secondMatrix is null)
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# if (secondMatrix is null) throw new ArgumentNullException(nameof(secondMatrix));
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# if (!TypeIsNumber<T>()) throw new ArgumentException($"{typeof(T)} is a data type that can't be multiplied."); int firstMatrixRowCount = firstMatrix.GetLength(0); int firstMatrixColumnCount = firstMatrix.GetLength(1); int secondMatrixRowCount = secondMatrix.GetLength(0); int secondMatrixColumnCount = secondMatrix.GetLength(1); if (firstMatrixColumnCount != secondMatrixRowCount) { if (firstMatrixRowCount == secondMatrixColumnCount) { return SwapDimensions(Multiply(SwapDimensions(secondMatrix), SwapDimensions(firstMatrix))); } throw new InvalidOperationException($"Matrix size mismatch. First matrix columns {firstMatrixColumnCount}, second matrix rows {secondMatrixRowCount}."); } T[,] resultMatrix = new T[firstMatrixRowCount, secondMatrixColumnCount]; for (int i = 0; i < firstMatrixRowCount; i++) { T[] firstMatrixRow = GetColumn(firstMatrix, i); for (int j = 0; j < secondMatrixColumnCount; j++) { T[] secondMatrixColumn = GetRow(secondMatrix, j); resultMatrix[i, j] = Multiply(firstMatrixRow, secondMatrixColumn); } } return resultMatrix; }
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# return resultMatrix; } /// <summary> /// Multiplies two matrices together. Assumes formatting is [rows][columns]. Will automatically /// correct this when wrong, except when both matrices have the same number of rows and columns. /// </summary> /// /// <example> /// If the return value is the answer you expect from multiplying <paramref name="secondMatrix"/> by <paramref name="firstMatrix"/> /// instead of what you intended, this typically means you've formatted your matrices as /// [columns][rows]. The following code example should fix your issue. /// /// Matrix.Multiply(Matrix.SwapDimensions(secondMatrix), Matrix.SwapDimensions(firstMatrix)); /// </example> /// <typeparam name="T">The datatype the matrices are. If it's a non numeric datatype, an <see cref="ArgumentException"/> will be thrown.</typeparam> /// <param name="firstMatrix">The first matrix to multiply.</param> /// <param name="secondMatrix">The second matrix to multiply.</param> /// <returns>The product of the two matrices.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> /// <exception cref="InvalidOperationException"></exception> public static T[][] Multiply<T>(T[][] firstMatrix, T[][] secondMatrix) { // Convert firstMatrix to a matrix of type T[,] T[,] convertedFirstMatrix = ConvertToTwoDimensionalArray(firstMatrix); T[,] convertedSecondMatrix = ConvertToTwoDimensionalArray(secondMatrix); T[,] convertedResultMatrix = Multiply(convertedFirstMatrix, convertedSecondMatrix); return ConvertToArrayOfArrays(convertedResultMatrix); }
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# return ConvertToArrayOfArrays(convertedResultMatrix); } /// <summary> /// Multiplies a matrix by a given multiplier. /// </summary> /// <typeparam name="T">The datatype the matrices are. If <typeparamref name="T"/>'s a non numeric datatype, an <see cref="ArgumentException"/> will be thrown.</typeparam> /// <param name="matrix">The matrix to multiply.</param> /// <param name="multiplier">The numeric value the matrix will be multiplied by.</param> /// <returns>The product of the matrix and the multiplier.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException"></exception> public static T[,] Multiply<T>(T[,] matrix, T multiplier) { if (matrix is null) throw new ArgumentNullException(nameof(matrix)); if (multiplier is null) throw new ArgumentNullException(nameof(multiplier)); if (!TypeIsNumber<T>()) throw new ArgumentException($"{typeof(T)} is a data type that can't be multiplied."); for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0;j < matrix.GetLength(1); j++) { matrix[i, j] *= (dynamic)multiplier; } } return matrix; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="matrix"></param> /// <param name="multiplier"></param> /// <returns></returns> public static T[][] Multiply<T>(T[][] matrix, T multiplier) => ConvertToArrayOfArrays(Multiply(ConvertToTwoDimensionalArray(matrix), multiplier));
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# /// <summary> /// Swaps the rows and columns of the passed matrix. /// </summary> /// <typeparam name="T">The data type of the matrix.</typeparam> /// <param name="matrix">The matrix you want to swap the dimensions of.</param> /// <returns>A copy of the matrix with the dimensions swapped.</returns> public static T[,] SwapDimensions<T>(T[,] matrix) { int rows = matrix.GetLength(0); int columns = matrix.GetLength(1); T[,] swappedMatrix = new T[columns, rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { swappedMatrix[j, i] = matrix[i, j]; } } return swappedMatrix; } /// <summary> /// Swaps the rows and columns of the passed matrix. /// </summary> /// <typeparam name="T">The data type of the matrix.</typeparam> /// <param name="matrix">The matrix you want to swap the dimensions of.</param> /// <returns>A copy of the matrix with the dimensions swapped.</returns> public static T[][] SwapDimensions<T>(T[][] matrix) => ConvertToArrayOfArrays(SwapDimensions(ConvertToTwoDimensionalArray(matrix))); private static T[,] ConvertToTwoDimensionalArray<T>(T[][] matrix) { T[,] result = new T[matrix.Length, matrix[0].Length]; for (int i = 0; i < matrix.Length; i++) { for (int j = 0; j < matrix[0].Length; j++) { result[i,j] = matrix[i][j]; } } return result; } private static T[][] ConvertToArrayOfArrays<T>(T[,] matrix) { T[][] result = new T[matrix.GetLength(0)][];
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# for (int i = 0; i < matrix.GetLength(0); i++) { result[i] = new T[matrix.GetLength(1)]; } for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { result[i][j] = matrix[i, j]; } } return result; } private static T Multiply<T>(T[] firstMatrix, T[] secondMatrix) { if (firstMatrix.Length != secondMatrix.Length) throw new InvalidOperationException($"Matrix size mismatch. First matrix columns {firstMatrix.Length}, second matrix rows {secondMatrix.Length}."); dynamic sum = 0; for (int i = 0; i < firstMatrix.Length; i++) { dynamic? itemOne = firstMatrix[i]; dynamic? itemTwo = secondMatrix[i]; sum += (T)(itemOne * itemTwo); } return (T)sum; } private static T[] GetRow<T>(T[,] matrix, int rowNumber) { var length = matrix.GetLength(0); var resultMatrix = new T[length]; for (int i = 0; i < length; i++) { resultMatrix[i] = matrix[i, rowNumber]; } return resultMatrix; } private static T[] GetColumn<T>(T[,] matrix, int columnNumber) { var length = matrix.GetLength(1); var resultMatrix = new T[length]; for (int i = 0; i < length; i++) { resultMatrix[i] = matrix[columnNumber, i]; } return resultMatrix; } private static bool TypeIsNumber<T>() { T? foo = default; if (foo is null) return false; try { T bar = (T)((dynamic)foo * foo);
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# try { T bar = (T)((dynamic)foo * foo); if (bar.Equals(foo)) return true; return false; } catch { return false; } } } } Here's my dilemma. I would like to make this as robust as possible, and as part of that, I originally decided to automatically swap the dimensions of the matrices if they aren't formatted in the way the code expects them to be ([rows, columns]). This works in most situations because the rows and columns are tpically not the same size, so unless the matrix's number of rows is equal to the number of columns, the code will work as intended. But if they are equal for both matrices, the method will return the wrong answer. I'm not looking to fix the issue so it magically knows to swap it anyways. I don't even know if that's possible. Instead I can just leave documentation that shows how to fix it (I already have that in the XML). Finally, the point. Is this decision a bad practice? Should I just let it run as is, and if there is an issue, leave it up to the user to fix it? If you were using the library without context, what would you expect? I also have a few additional questions, but these are secondary to the main point. Is there a cleaner way to have these methods work for more than just one data type? Currently I just let the user define the type, but to do multiplication, I have to cast to dynamic. I feel like there's a better way to do that but I don't know what it is. Aside from all of the type casting, are there any glaring inefficiencies that I should fix? I can't find any myself, but I feel like I'm missing something obvious.
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c# Answer: I’m glad you’re asking / exploring the question. Is auto-magically (silently) “fixing” the input a bad practice? Yes. Why is that? It’s much nicer to alert the caller to a code defect, a contract violation, with informative diagnostic than to conceal the latent bug and sometimes give wrong answer without warning. When caller gets fatal diagnostic, the source code will soon be improved with a helpful edit, so it is good to “fail hard”. Otherwise, the source is much less likely to be improved.
{ "domain": "codereview.stackexchange", "id": 45426, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#", "url": null }
c++, c++14 Title: Fill vector of unique_ptr only with required derived types and enforce multiplicities constraints Question: I wrote a function that accepts a destination vector and a vector of all the types that are currently available. Its job is to iterate over all the available types (strings) and for each type, if it's required, the respective derived class should be added to the vector. I also want to enforce a constraint that only one of each derived can be added to the vector (in the future, this constraint might change and some types will be able to appear in the destination more than once). I feel like there might be a more elegant way to solve it, and would appreciate a review on how I can better it. (I considered using an unordered set for the version with constraint of 1 per type, but then how would I ensure that I found exactly one of a type in the available vector? Once I erase a type from the set I can't track if I encountered another one, which is an error state.) This is a simplistic version of the code (C++14): #include <string> #include <vector> #include <unordered_map> #include <cassert> #include <memory> class Base { public: virtual ~Base() {} }; class DerivedA : public Base { public: static std::string getType() { return "DerivedA"; } }; class DerivedB : public Base { public: static std::string getType() { return "DerivedB"; } }; class DerivedC : public Base { public: static std::string getType() { return "DerivedC"; } }; void fillRequired(std::vector<std::unique_ptr<Base>>& dstVector, const std::vector<std::string>& availableTypes) { std::unordered_map<std::string, int> requiredTypeCount = { {DerivedA::getType(), 0}, {DerivedB::getType(), 0}, {DerivedC::getType(), 0}};
{ "domain": "codereview.stackexchange", "id": 45427, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++14", "url": null }
c++, c++14 for (const auto& availableType : availableTypes) { auto it = requiredTypeCount.find(availableType); if (it != requiredTypeCount.end()) { requiredTypeCount[availableType]++; if (availableType == DerivedA::getType()) { dstVector.emplace_back(std::make_unique<DerivedA>()); } else if (availableType == DerivedB::getType()) { dstVector.emplace_back(std::make_unique<DerivedB>()); } else if (availableType == DerivedC::getType()) { dstVector.emplace_back(std::make_unique<DerivedC>()); } } } for (const auto& requiredType : requiredTypeCount) { assert(requiredType.second == 1 && "Each type must be present exactly once"); } } Thanks (: Answer: There are various ways to approach this problem. What the best way is will depend on things like how often this function is called, and how many elements requiredTypeCount and availableTypeCount will have in a real program. If you wish for elegance, then I would want to write it like so: void fillRequired(std::vector<std::unique_ptr<Base>>& dstVector, const std::set<std::string>& availableTypes) { static const std::set<std::string> requiredTypes = { DerivedA::getType(), DerivedB::getType(), DerivedC::getType() }; std::set_intersection(requiredTypes.begin(), requiredTypes.end(), availableTypes.begin(), availableTypes.end(), std::back_inserter(dstVector)); }
{ "domain": "codereview.stackexchange", "id": 45427, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++14", "url": null }
c++, c++14 I changed the type of the parameter availableTypes to a std::set; this doesn't allow duplicates, so this function doesn't have to worry about that anymore. You could always add another function that builds this std::set from a std::vector and that does assert() when it finds duplicates. Then requiredTypes is also changed to a std::set. But it doesn't need to count anymore, so we can make it static const; this means it doesn't have to build this set from scratch every time the function is called. Now that we have two ordered containers without duplicates, we can use std::set_intersection() to find the intersection between the two sets. We then use std::back_inserter() to push the elements that are in both sets into dstVector. But oops, that just tries to insert std::strings into dstVector, but instead we want to insert pointers to newly created objects. Unfortunately there is no way in the standard library that we can use to pass a lambda instead, but Boost has a handy function_output_iterator that we could use: std::set_intersection(…, boost::function_output_iterator( [&](const std::string& name) { if (name == DerivedA::getType()) { dstVector.emplace_back(std::make_unique<DerivedA>()); } else … } ) ); You could also write your own output iterator if you don't want to rely on Boost (it's not very hard). But this isn't so elegant anymore. I would at the very least create a separate function that, given a std::string, returns a std::unique_ptr<Base>. That would simplify both your original code and the code I suggested here. Some other ideas:
{ "domain": "codereview.stackexchange", "id": 45427, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++14", "url": null }
c++, c++14 Consider returning a std::vector<std::unique_ptr<Base>> instead of passing it as an out parameter. Consider using typeid() instead of having a getType() function. Comparing the result of typeid() might also be faster than comparing std::strings. assert() becomes a no-op when NDEBUG is defined. This might happen automatically when using some build systems and when generating release builds. If you don't want that to happen, maybe calling std::abort() or throwing exceptions might be better. If both the contents of availableTypes and requiredTypes are known at compile-time, then you could use template programming to fill dstVector at compile-time. Consider moving to at least C++17; this adds std::apply() which allows you to iterate over the types contained in a std::tuple. This can be used to avoid a long and repetitive if-else` sequence.
{ "domain": "codereview.stackexchange", "id": 45427, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++14", "url": null }
c++, search, binary-search Title: Incremental upper bound in sorted range Question: Since initial question Increasing binary search for mismatch in sorted range contained defects in code and can confuse the readers, here is the updated version of the question. Is the code below correct and efficiently implemented to solve the following task? Can this code be improved with reuse of other C++ Standard Library algorithms without additional libraries? Functional specification Having a very large vector (gigabytes) with sorted repeated values with exponential distribution (like 50% of values occur only once, 25% only two times in a row, 12.5% about 3 times in a row, etc.) provide a function to get iterator to the next value (different than current) in std::vector. The algorithm is going to be used with many predicates for the same vector of data. Performance is key both from perspective CPU loading and memory bandwidth. Actual values in the vector are not integers and comparison is time-consuming operation, so using std::upper_bound is not effective here, since it involves about log2(n) comparisons while the needed element often is very close. Design Having requirements on limited data bandwidth and having many predicates for the same data prevents us from pre-calculating offsets to needed positions. Based on values frequency distribution, it is more effective to start with range 1 and multiply the range with every step, this gives about 30% of speed up against pure std::upper_bound usage. The code The fully functional demo: #include <algorithm> #include <iostream> #include <vector> // Algorithm works similarly to std::upper_bound, but uses element specified by iterator *first* to find first element in range which is not equal to it. template<class RandomIt, class Pred> constexpr RandomIt incremental_upper_bound(RandomIt first, RandomIt last, Pred comp, size_t starting_search_range = 1) { if (first == last) return last; const auto current = *first++;
{ "domain": "codereview.stackexchange", "id": 45428, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, search, binary-search", "url": null }
c++, search, binary-search const auto current = *first++; size_t short_search_range = starting_search_range; while (first != last) { const auto short_search_end = (size_t)std::distance(first, last) < short_search_range ? last : std::next(first, short_search_range); first = std::upper_bound(first, short_search_end, current, comp); if (first == last || comp(current, *first)) return first; short_search_range *= 2; } return last; } int main() { std::vector<int> v = { 1, 2, 2, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7 }; for (auto it = v.begin(); it != v.end(); ) { auto it_next = incremental_upper_bound(it, v.end()); std::cout << "Number of elements with value " << *it << " is " << it_next - it << "\n"; // Some work on the range it = it_next; } return 0; } Measurements Per advice from G. Sliepen I’ve done some measurements in terms of number of comparisons and performance. To show the trends, I tested on tiny, medium and large text bases. The suffix arrays for real texts have some specifics, the next unique element comes very fast (example for 9 lexems long strings limit for comparison), so real offsets statistics are like this: Offset Amount in data % 1 463682831 98.49% 2 6519364 1.38% 3 400000 0.08% 4 124922 0.03% 5 18276 0.00% 6 8421 0.00% 7 5086 0.00% 8 2802 0.00% 9 1941 0.00% 10 1727 0.00% Here are the results: std::upper_bound incremental_upper_bound Tiny text(text size: 363 lexems; dictionary size: 153 lexems Amount of comparisons (predicate calls) 1943 551 Medium size text(text size: 69 910 995 lexems; dictionary size: 878 993 lexems) Amount of comparisons (predicate calls) 1 428 018 106 115 013 024 Running time, seconds 33 7 Large text(text size: 583 654 363 lexems; dictionary size: 2 791 370 lexems) Amount of comparisons (predicate calls) 13 122 916 104 943 337 060 Running time, seconds 436 79
{ "domain": "codereview.stackexchange", "id": 45428, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, search, binary-search", "url": null }
c++, search, binary-search Amount of comparisons (predicate calls) 13 122 916 104 943 337 060 Running time, seconds 436 79 Conclusion The results are as expected. Let’s see the last case. For the index array std:upper_bound needs about 28 iterations on average to find the answer and incremental_upper_bound takes two on average, so the comparisons rate in about 14 times. Of course, this is the data specifics which makes the improvement so huge. When we mostly need to find the next unique elements in one or two positions from current, it is different from other datasets. But, anyway, on large data std:upper_bound is memory-bounded and not cache-friendly, making huge steps could be quite expensive for such task as "searching for the next element, not equal to current". The incremental_upper_bound helps to localize work and increase caching benefits.
{ "domain": "codereview.stackexchange", "id": 45428, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, search, binary-search", "url": null }
c++, search, binary-search Answer: current should be a reference If comparisons are time-consuming, then the values you are comparing are probably non-trivial. Your declaration of current makes a copy of a value, which can be expensive, or perhaps even impossible if the value type of the container is non-copyable. Making current a reference solves this. Measure how many comparisons it actually takes According to cppreference.com, std::upper_bound() uses at most \$\log_2(last - first) + O(1)\$ comparisons. However, the actual number of comparisons depends on the exact implementation of the standard library, and where in the range you pass it the upper bound really is. For example, there is no guarantee that it does its first comparison with the last element in the range. So I would create a class with a comparison operator that counts how often it is called. Then you can call your incremental_upper_bound() on a vector with the desired distribution, and check how many comparisons it takes. Then you can also check if different ways to initialize and update short_search_range are better or worse. It might also make sense to avoid using std::upper_bound(), and do the search yourself. That way you have full control of when comparisons are made.
{ "domain": "codereview.stackexchange", "id": 45428, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, search, binary-search", "url": null }
c++, collections, c++20, memory-optimization, set Title: Collection that uses a bitset to store a huge set of unique integers from a given range (rev. 1)
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set Question: Some (skippable) context: I'm writing program that minimizes an arbitrary logical function. Such function takes an unsigned integer as an argument and returns either true or false. The input to my program is a list of all values for which the minimized function returns true. Those values are called "minterms". Because I want to handle functions that take arguments up to 32 bits, the number of minterms may reach billions and I need a way to effectively store them. Description of the code: This is a collection that stores set of unique 32-bit unsigned integers from range 0..n where n is decided at runtime and can be as high as 2^32 - 1. In a typical case, the number of stored integers is close to the half of the size of the range. The primary concern while writing this, was RAM usage. Using std::vector<std::uint32_t> would result in 16 GB of memory in the worst case. Instead, I've opted for using a std::vector<bool> as a bitset. Each bool in it represents an integer equal to its the index in the vector, where true means that the number is present and false that it is not. This reduces the memory usage to "merely" 512 MB. Another, also very important concern, is the speed. This is the reason for which almost everything is inlined and contained in the header file. Fortunately, this way of storing the data allows for checking and storing arbitrary values in O(1) time and this is the may mode of interaction with the data. The iterator is not invalidated when elements are added / removed, which is useful in a few algorithms. I tried to make this code work in all the popular compilers. I also avoided using any external libraries to make it compile out of the box for every user. Purpose of the review: I think the algorithm I'm using is sound and decently optimized but of course I welcome any suggestions on how to make this code faster. The main purpose of the review, however, is too gauge the quality and readability of the code.
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set The main purpose of the review, however, is too gauge the quality and readability of the code. I have quite a lot of experience with C++ but I'm mostly self-learned. I've never worked professionally with other people knowing this language so I might be not aware of some more obscure conventions in the language. Please tell me if I'm doing anything that an average professional C++ programmer would consider weird. One thing that I am aware of is that my naming convention does not match the one from the standard library. I just like the Java naming convention. Do you think my code is readable? Are any names unclear? Should I add an explanatory comment somewhere? Are there any aspects of the C++ language that would be in some way helpful but I seem unaware of? E.g. things like the attribute [[nodiscard]]. Roast my code: This code uses 2 headers from my project that are not included in the review:
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set "Minterm.hh" defines the type Minterm which is just an alias to std::uint_fast32_t. "global.hh" defines a value maxMinterm which depends on the program's input but it doesn't change after its initialization at the beginning. It's value is in range from 0 to 2^32 - 1. Minterms.hh: #pragma once #include <algorithm> #include <cstddef> #include <cstdint> #include <iterator> #include <vector> #include "global.hh" #include "Minterm.hh"
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set class Minterms { std::vector<bool> bitset; std::size_t size = 0; public: using overlapping_t = std::vector<Minterm>; class ConstIterator { const Minterms &minterms; std::uint_fast64_t i; ConstIterator(const Minterms &minterms, const std::uint_fast64_t i) : minterms(minterms), i(i) {} friend class Minterms; public: [[nodiscard]] bool operator==(const ConstIterator &other) const { return this->i == other.i; } [[nodiscard]] bool operator!=(const ConstIterator &other) const { return this->i != other.i; } inline ConstIterator& operator++(); inline ConstIterator& operator--(); [[nodiscard]] Minterm operator*() const { return static_cast<Minterm>(i); } }; Minterms() : bitset(static_cast<std::uint_fast64_t>(::maxMinterm) + 1, false) {} [[nodiscard]] bool operator==(const Minterms &other) const { return this->bitset == other.bitset; } [[nodiscard]] bool operator!=(const Minterms &other) const { return this->bitset != other.bitset; } [[nodiscard]] bool isEmpty() const { return size == 0; } [[nodiscard]] bool isFull() const { return size - 1 == ::maxMinterm; } [[nodiscard]] std::size_t getSize() const { return size; } [[nodiscard]] std::size_t getCapacity() const { return bitset.size(); } [[nodiscard]] bool check(const Minterm minterm) const { return bitset[minterm]; } [[nodiscard]] inline overlapping_t findOverlapping(const Minterms &other) const; // Optimized for when there is little to none of them. inline bool add(const Minterm minterm); inline void add(const Minterms &other, const std::size_t overlappingCount); inline bool remove(const Minterm minterm); [[nodiscard]] inline ConstIterator begin() const; [[nodiscard]] ConstIterator end() const { return {*this, bitset.size()}; } [[nodiscard]] ConstIterator cbegin() const { return begin(); }
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set [[nodiscard]] ConstIterator cbegin() const { return begin(); } [[nodiscard]] ConstIterator cend() const { return end(); } #ifndef NDEBUG void validate() const; #endif };
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set Minterms::ConstIterator& Minterms::ConstIterator::operator++() { for (++i; i != minterms.bitset.size() && !minterms.bitset[i]; ++i) { } return *this; } Minterms::ConstIterator& Minterms::ConstIterator::operator--() { for (--i; i != 0 && !minterms.bitset[i]; --i) { } return *this; } Minterms::overlapping_t Minterms::findOverlapping(const Minterms &other) const { overlapping_t overlapping; std::set_intersection( this->cbegin(), this->cend(), other.cbegin(), other.cend(), std::back_inserter(overlapping)); return overlapping; } bool Minterms::add(const Minterm minterm) { const bool previous = check(minterm); if (!previous) { bitset[minterm] = true; ++size; } return !previous; } void Minterms::add(const Minterms &other, const std::size_t overlappingCount) { std::transform( other.bitset.begin(), other.bitset.end(), this->bitset.begin(), this->bitset.begin(), std::logical_or<bool>()); this->size += other.size - overlappingCount; } bool Minterms::remove(const Minterm minterm) { const bool previous = check(minterm); if (previous) { bitset[minterm] = false; --size; } return previous; } Minterms::ConstIterator Minterms::begin() const { ConstIterator iter{*this, 0}; if (!bitset.empty() && !bitset[0]) ++iter; return iter; } Minterms.cc: #include "./Minterms.hh" #include <cassert> #ifndef NDEBUG void Minterms::validate() const { std::size_t actualCount = 0; for ([[maybe_unused]] const Minterm minterm : *this) ++actualCount; assert(size == actualCount); } #endif
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set Answer: Don't call the class itself Minterms While your program might need to store a list of "minterms", the data structure you are using for this doesn't care what is stored in it. I would call the class you make Bitset or something like that, and then in your actual code you write something like: Bitset minterms(…); Consider not creating a class Instead of creating your own class that wraps a std::vector<bool>, consider whether you can just use a std::vector<bool> directly. Most of your member functions do things you could directly do on a std::vector<bool>. I see two things that are different: You have added a way to iterate over only the set bits in the bitset. However, you can add your own get_set_bits() function that takes a std::vector<bool> as an input, and returns a range that can be iterated over and that returns the indices of all the set bits. You can reuse your ConstIterator for that. You keep track of the number of set bits. While you could call something like std::ranges::count() on a std::vector<bool> to count the number of set bits, that would have to iterate over the whole vector, which might take a lot of cycles if maxMinterm is very large.
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
c++, collections, c++20, memory-optimization, set If you don't need to know the number of set bits often and/or efficiently, then I would just use std::vector<bool> directly. Use std::bitset if maxMinterm is known at compile time If you know maxMinterm at compile time, then you can use std::bitset instead of a std::vector<bool>. It has a member function count() that returns the number of set bits. Make it look and behave like a standard library container If you do need to create your own class, then at least make it look and behave like the containers from the standard library. This way, someone already familiar with the STL doesn't need to learn that your class uses isEmpty() instead of empty() to check if the container is empty, instead of empty(). Furthermore, the standard algorithms that work on STL containers can also work on your container, but only if you provide the same interface. It also makes it easier to replace one type of container with another. Remove functions that don't need to members. For example, findOverlapping() just calls std::set_intersection(). The user of your class can call that directly themselves on your class if you give it the right interface. Then they get more flexibility, for example if they want to do something other than have the result back-inserted into a std::vector<Minterm>. Unsafe add() The version of add that takes a reference to another Minterms and an overlappingCount is unsafe. It trusts that overlappingCount is passed correctly. But what if it is not? Then this->size will be incorrect. I would avoid the issue completely by just writing: void Minterms::add(const Minterms &other) { for (auto minterm: other) { add(minterm); } } About operator--() With standard library iterators, it is never valid for the caller to decrement an iterator past begin(). So you don't need the check for i != 0, and can just write: Minterms::ConstIterator& Minterms::ConstIterator::operator--() { while (!minterms.bitset[--i]) {} return *this; }
{ "domain": "codereview.stackexchange", "id": 45429, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, collections, c++20, memory-optimization, set", "url": null }
beginner, php, ruby, ruby-on-rails Title: Session Logic for User Verification in Rails Migration Question: This is a logic to create sessions on RoR 7.1.2 based on the last version of the website which was in vanilla PHP, with the upgrade I have to deal with the users that were already signed up but not have a password_digest attribute on his database just a password hashed by PHP which RoR with the gem Bcrypt cant understand, so with this logic it can access no matter were old or new users. class SessionsController < ApplicationController def create @user = find_user_by(params[:user][:username]) if @user&.authenticate(params[:user][:password]) success_login elsif php_authenticate?(params[:user][:password]) success_login else display_error('Invalid user or password') end end private def find_user_by(username) user = User.find_by(username: username) return user if user user = User.find_by(email: username) return user if user nil end def php_authenticate?(password) @user&.password_php && php_auth(password) end def php_auth(password) php_file = 'app/controllers/helpers/auth_password.php' output = `php #{php_file} '#{password}' '#{@user&.password_php}'` output == 'true' end def display_error(error) flash[:error] = error redirect_to login_path end def success_login session[:user_id] = @user.id redirect_to root_path end end auth_password.php: $password = $argv[1]; $hased_password = $argv[2]; if (password_verify($password, $hased_password)) { echo 'true'; } else { echo 'false'; }
{ "domain": "codereview.stackexchange", "id": 45430, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, php, ruby, ruby-on-rails", "url": null }
beginner, php, ruby, ruby-on-rails if (password_verify($password, $hased_password)) { echo 'true'; } else { echo 'false'; } Answer: This mostly looks good and sensible, but it does raise some serious concerns. naming Using a php_ prefix is accurate, and perhaps a good name. But consider using a legacy_ or v1_ prefix instead. Then we'll be in good shape if PHP rears its undying head again and muscles its way into the codebase in some different form. hash pattern if @user&.authenticate(params[:user][:password]) success_login elsif php_authenticate?(params[:user][:password]) success_login We're doing if A --> success elsif B --> success, which is more succinctly phrased as if A || B --> success. But this is security critical code, and we're expanding the attack surface to be larger than necessary. Can't we examine some prefix of the hash, or test a regex, and dispatch on that to the appropriate authentication routine? For example, if you look at a FreeBSD or Linux /etc/passwd or /etc/shadow file, there may be half a dozen back-compatible hashing schemes supported. Does the OS attempt if A or B or C or D or ... ? No, it dispatches based on the hash scheme version, which was carefully encoded to support such dispatching. collapsed namespaces def find_user_by(username) user = User.find_by(username: username) return user if user user = User.find_by(email: username) return user if user
{ "domain": "codereview.stackexchange", "id": 45430, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, php, ruby, ruby-on-rails", "url": null }
beginner, php, ruby, ruby-on-rails user = User.find_by(email: username) return user if user Usernames are drawn from one namespace; roughly they match /^\w+$/. Email addresses drawn from another, and we definitely expect they shall contain an @ at-sign, e.g. /^[\w.-]+@[\w.-]+$/. (Yeah, yeah, I know, localpart can contain more valid characters, and with IDN so can globalpart.) I would prefer to only probe by email address for inputs that are known to contain an @ at-sign. More generally, there's a regex that describes valid username spellings -- only probe the database upon a match. And similarly for valid email spellings. shell escapes This is the one that makes me, and little Bobby Tables, very nervous: def php_auth(password) ... output = `php #{php_file} '#{password}' '#{@user&.password_php}'`
{ "domain": "codereview.stackexchange", "id": 45430, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, php, ruby, ruby-on-rails", "url": null }
beginner, php, ruby, ruby-on-rails There's two different interpreters involved: bash + php. Each is powerful. Each does their own interpretation of argument characters. There is room to lose. Now, if we just ask for ls output, there's no shell interpreter involved, as ruby does fork / exec of an ls child. But if the backtick command can contain e.g. a | pipe symbol, then ruby definitely delegates to the shell, which in turn delegates to spawned children. You should have a regex that describes a valid password hash, e.g. /^[0-9a-f]+$/. Only pass that password argument to a child if it matches the regex, that is, only if it could possibly be valid. Php accepts a wide variety of command line options, which can potentially do interesting things for an attacker. I don't want to know about them. I don't want to have to reason about the properties of the attack surface the current proposed code opens up for an attacker. Much better to be conservative in what you send down to the child process. specification The OP question didn't really flesh out the input space in ways that would let an implementer distinguish between good and bad scenarios. automated tests This submission contains no integration or unit tests that would increase our confidence in the ability of target code to reject carefully crafted attack inputs. This code fails to accomplish its stated goals, which is to securely verify client credentials in the presence of attacker clients. I would not be willing to delegate or accept maintenance tasks on this codebase in its current form.
{ "domain": "codereview.stackexchange", "id": 45430, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, php, ruby, ruby-on-rails", "url": null }
c++, strings, search Title: Fast search for the longest repeating substrings in large text (Rev.3) Question: This is the third iteration of the Fast search for the longest repeating substrings in large text (Rev.2) code review. Special thanks goes to G. Sliepen who conducted the first two reviews. Functional specification Having a large text and already built suffix array find the longest substrings (limited by the number of repetitions) getting benefit from already existing prefix array, if reasonable. Provide the version which would benefit from multithreading keeping the code as simple as possible. Implementation The fully functional demo. Reservation: current implementation utilizes execution policies, so using ranges/projections/views under the question; would work if multi-threading requirement from above met. The further details make sense only as addition to aforementioned second Code Review with answer to it. Answers to the questions on previous revision code review On the dilemma “this number or more” or “exactly this number” it is really funny. I tested both on real texts and real environment they give much the same results; the difference is subtle. Main goal was to clean up text base from text duplicates (like the same story in different collections of works, etc.). Even more, the same goes to duplication defect from the first version. With this I mean that all defects, of course, must be fixed and option for different way of search should be provided, but in real environment even “slightly erroneous version” is “good enough”. Just funny side note. I tested both versions of calculateAdjacents with std::for_each and with std::transform_reduce on real data. You are correct, no significant difference in performance, which is highly reasonable, but since I am aiming to port this to GPU with many cores later, I decided to stay with std::transform_reduce which should give some speed up on GPU, I believe.
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search Here is the current implementation of calculateAdjacents: // Returns found sequence(s) length size_t calculateAdjacents(const Index<>& index, std::vector<index_t>& adjacent_matches, size_t repetitions, bool strong_repetition_count) { std::fill(std::execution::par_unseq, adjacent_matches.begin(), adjacent_matches.end(), 0); size_t max_match_length = std::transform_reduce(/*std::execution::par_unseq,*/ index.begin(), index.end() - (repetitions - 1), size_t(0), [&](size_t max_match_length, size_t match_length) -> size_t { return std::max(max_match_length, match_length); }, [&](const auto& item) -> size_t { const auto& text = index.text; size_t idx = &item - std::data(index.index); size_t match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, (repetitions - 1)); if (strong_repetition_count) { // Not more than min_repetitions times before item if (&item > std::data(index.index)) { size_t prev_match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, -1); if (prev_match_length == match_length) return 0; } // Not more than min_repetitions times after (item+repetitions-1) if ((size_t)((&item + repetitions) - std::data(index.index)) < index.size()) { size_t next_match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, repetitions); if (next_match_length == match_length) return 0; } } adjacent_matches[idx] = (index_t)match_length; return match_length; }); return max_match_length; }
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search return match_length; }); return max_match_length; } On keeping the findMatchLength, this is kind of adherence to Occam's razor principle to avoid unnecessary entities and a kind of rule of thumb like “If you can’t explain in simple words (preferably by function name) what it does generically, out of context of current task, avoid creating it or at least avoid making it visible to client. For this particular function I can’t explain in simple words what it does without this task context. On the “I would be happy to avoid this `std::fill' at the beginning of calculateAdjacents function, but I am not sure if this is possible.”, I most likely wrongly worded my intention. I mean I want to avoid clearing the vector this way or another. I am not concerned with the way it is done, I am concerned with the algorithm which requires it and I am looking for a way to avoid such performance-consuming operation with high memory-bounding. I will do my best to change the algorithm to avoid this in the subsequent versions. At the same time, I don’t want to move it to calculateAdjacents, because this will cause allocating and releasing this array on each function call. Taking into account that its size equal to text size, on large text bases this could be quite expensive; this is the reason I create the array on a higher level. In real code I wouldn't use std::string and will use std::vector to keep identifiers (unsigned int) of lexems (actually, even a bit deeper – identifiers of categories or clusters of lexem, but this doesn’t matter at the moment). That’s why in the next revision I will move from std::string to std::vector just to better understand how to manipulate with sequences in absence of std::string and std::string_view functions. Major changes
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search Major changes Since in real project I will use lexem identifiers instead of plain text, I did some “emulation” in code for this, making pseudo tokenizer which for the sake of simplicity just converts characters’ codes to ints. This is just a trick to go to real types I use and move from std::string and std::string_views. Another step to make algorithm generic, meanwhile. So, I introduced the: using lexem_t = unsigned int; using index_t = unsigned int; Function parameters text and index replaced with Index template which will be covered below. “Subtle” defect for the "this number or more" version (“weak count”) mentioned by G. Sliepen has been fixed in the collectRepeatingSubstrings function. The max_repetitions threshold removed; it is not needed even on large data sets, no significant performance impact or memory footprint on real data. The collectRepeatingSubstrings function reworked according recommendations. New version is much more readable. Here it is: struct SubstringOccurences { std::span<const lexem_t> sequence; std::vector<index_t> pos; }; std::vector<SubstringOccurences> collectRepeatingSubstrings(const Index<>& index, std::vector<index_t> adjacent_matches, size_t repetitions, size_t max_match_length) { std::vector<SubstringOccurences> result; size_t j = 1; for (size_t i = 0; i < adjacent_matches.size() - 1; i+=j) { if (adjacent_matches[i] == max_match_length) { result.emplace_back( std::span(index.text.begin() + index[i], max_match_length), std::vector(&index[i], &index[i + repetitions]) ); } for (j = 1; i+j < adjacent_matches.size() && max_match_length == findMatchLengthWithOffsetInSuffixArray(index, i, j); ++j) ; } return result; } The findMatchLength function inlined to findMatchLengthWithOffsetInSuffixArray to avoid swamping the namespace.
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search Here is how it looks like now: size_t findMatchLengthWithOffsetInSuffixArray(const Index<>& index, const size_t idx, ptrdiff_t offset) { const auto& text = index.text; return std::mismatch(text.begin() + index[idx], text.end(), text.begin() + index[idx + offset], text.end()).first - (text.begin() + index[idx]); } Introduced option strong_repetition_count to control the way the algorithm handles repetitions parameter: “find substring with exact number of repetitions” = “strong count” and “find substring with this number of repetitions or more” = “weak count”. My concerns on this code I started with a dozen lines of code and now it grew to 150+ lines of code most of which is still not reusable. I had one function, now I have 2 new types and 4 functions. Well, some defects were fixed which complicated the code a bit, but mostly I paid for functional decomposition. I am still in two minds that the price is reasonable. Anyway, this is still not a final version, so, let’s compare the final result. While the function findRepeatedSubsequences is a kind of client function, I don’t like that std::cout (or any other stream) is build-in here. Of course, I can return new object RepeatedSubsequences from this function which will collect all the results and overload the operator << for this type in order to be able to output it in any stream in usual manner, but this will additionally complicate the code and will have performance and memory footprint on storing these results. Here is how the functions looks like now: void findRepeatedSubsequences(const Index<>& index, size_t max_repetitions, bool strong_repetition_count = true) { std::vector<index_t> adjacent_matches(index.size());
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search for (size_t repetitions = 2 ; repetitions <= max_repetitions; ++repetitions) { size_t sequence_length = calculateAdjacents(index, adjacent_matches, repetitions, strong_repetition_count); if (sequence_length < 1) continue; std::cout << "Longest equal sequence(s) repeated " << repetitions << " times is " << sequence_length << " chars.\n"; for (auto sequence : collectRepeatingSubstrings(index, adjacent_matches, repetitions, sequence_length)) { std::cout << "The sequence at position(s): ("; const char* delimiter = ""; for (auto pos : sequence.pos) { std::cout << delimiter << pos; delimiter = ","; } std::cout << "): "; std::copy(sequence.sequence.begin(), sequence.sequence.end(), std::ostream_iterator<char>(std::cout)); std::cout << "\n"; } std::cout << "\n"; } } Index class I had a special homework from G. Sliepen to figure out the name for the structure to wrap up references to text and index. My way of thinking is following: I really need only the index and it would be nice if reference to text is stored somehow in it. It would be nice to have this index type transparent for the client code in order to avoid client code like index.index as much as possible. (I still have it in std::data(index.index), which could easily be replaced with index.begin() in this context, but I eager to learn how to handle this case, as well.
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search Before these code reviews I raised the question The best place to store index to data where I didn’t get better proposals than my way to wrap up the references to index and indexed text into Index structure: template <typename LexemType=lexem_t, typename IndexType = index_t> struct Index { const std::vector<LexemType>& text; const std::vector<IndexType>& index; public: decltype(index.begin()) begin() const { return index.begin(); } decltype(index.end()) end() const { return index.end(); } size_t size() const { return index.size(); } const IndexType& operator[] (size_t idx) const { return index[idx]; } }; Some reservations: I made it a structure to avoid excessive accessors. I don’t think they would help much here. Of course, having text and index public makes redundant exposing begin(), end(), size() and operator[]; I made it to simplify client code. Other code snippets Since I moved from std::string to std::vector to keep the sequences, I reworked SubstringOccurences to: struct SubstringOccurences { std::span<const lexem_t> sequence; std::vector<index_t> pos; };
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search I hope, this is the correct way and place to use std::span. Generalization One of the questions from G. Sliepen was “Why limit it to strings at all? It seems to me that you could make this work for any kind of range.”. The only reason I am keeping this not generic is that I want to keep implementation in source files, not in headers in order to maximize insulation (physical encapsulation), reduce compile time and keep visible interfaces free of utility functions. If there is a way to make them generic without exposing them to header files, it would be nice to know. If not and it goes to header files, there is another question. The findMatchLengthWithOffsetInSuffixArray is not generic, I can’t explain to user what it does without the context of the task, as well as calculateAdjacents and collectRepeatingSubstrings. What is the best way to hide them from client? Create nested utility namespace? Wrap up everything in class which will be able to hold the results and support operator << and will provide encapsulation? Other methods? Is there any way to improve this code? Any mistakes or issues? Could you please help conducting further steps of code review? Answer: Don't use decltype() unnecessarily In Index you have this member functions: decltype(index.begin()) begin() const { return index.begin(); } First of all, you are repeating index.begin() twice. What if the body of your begin() is much more complicated? It quickly becomes very complicated to declare the return type like that. You could just use decltype(auto). However, why do you need decltype() at all here? It would only make sense if you were forwarding the return value of a function whose return type you don't know. But here it is clear: index.begin() returns an iterator by value. It wouldn't ever make sense for it to return a reference. So just write: auto begin() const { return index.begin(); }
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search Be consistent If you are using return type deduction for begin() and end() in Index, why not use the same for size() and operator[]()? If you make Index a template so you can vary LexemType and IndexType, why isn't SubstringOccurences a template in the same way? And why are calculateAdjacents() and the other functions that take an index as input templates? Either nothing should be a template here, or everything should. index and text are not private In struct Index, nothing is private. You added the member functions begin(), end(), size() and operator[]() to avoid other code from directly accessing the member variables. But other code is accessing those member functions directly anyway. Again, be consistent: either just make it a simple struct that is just holding two vectors without member functions, or make it a class that makes all member variables private and only allows access via member functions. Clearing adjacent_matches Inside the call to std::transform_reduce() you only ever write to adjacent_matches. You visit every index from the start to the end minus repetitions - 1. So if you ensure you always write to adjacent_matches[idx] in the transformation function, then the only thing left to do afterwards is to clear the last repetitions - 1 elements. Remove responsibilities from findRepeatedSubsequences() While the function findRepeatedSubsequences is a kind of client function, I don’t like that std::cout (or any other stream) is build-in here. Indeed, that's bad. This function is now responsible both for finding repeated subsequences (as its name implies), and for formatting the result and printing it to std::cout. It should just do the former. Of course, I can return new object RepeatedSubsequences from this function which will collect all the results That's not an unreasonable way to do it. and overload the operator << for this type in order to be able to output it in any stream in usual manner,
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search No. Again, this unnecessarily complicates RepeatedSubsequences. What if you don't want to output the result to a stream, but do something else with it? Or what if I want to be able to format the output as JSON or XML instead of printing something human readable? You can't just add more and more member functions to that class just to cover all possible uses. It might never end. Just make sure other code can access the results stored in it. [this] will have performance and memory footprint on storing these results. That is a valid concern. There are various ways to go about this. First, I would remove the loop from findRepeatedSubsequences(), so it only finds repeated subsequences for one value of repetitions. If you are worried about repeated allocation and initialization of adjacent_matches, you can make it a static variable: RepeatedSubsequences findRepeatedSubsequences(const Index<>& index, size_t repetitions, bool strong_repetition_count = true) { static std::vector<index_t> adjacent_matches; adjacent_matches.resize(index.size()); RepeatedSubsequences result; result.sequence_length = calculateAdjacents(index, adjacent_matches, repetitions, strong_repetition_count); result.repeating_substrings = collectRepeatingSubstrings(index, adjacent_matches, repetitions, result.sequence_length)); return result; }
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search return result; } Now you can create a printRepeatedSubsequences() function that formats the contents of a RepeatedSubsequences object. Another option is to keep the outer for-loop in findRepeatedSubsequences(), but pass a callback function to it that will be called for every iteration: template<typename Callback> void findRepeatedSubsequences(const Index<>& index, size_t max_repetitions, bool strong_repetition_count = true, Callback callback) { std::vector<index_t> adjacent_matches(index.size()); for (size_t repetitions = 2 ; repetitions <= max_repetitions; ++repetitions) { RepeatedSubsequences result; result.sequence_length = calculateAdjacents(index, adjacent_matches, repetitions, strong_repetition_count); if (sequence_length < 1) continue; result.repeating_substrings = collectRepeatingSubstrings(index, adjacent_matches, repetitions, sequence_length); callback(result); } } The caller can then pass printRepeatedSubsequences() as the callback function, or whatever else it likes. But I think it is more complicated than necessary in this case. About the code size I started with a dozen lines of code and now it grew to 150+ lines of code most of which is still not reusable. The code from the first revision you posted here was more than two dozen lines of code, even excluding buildPrefixArrayIndex(). Some of the growth comes from nicer formatting of the output, and from fixing some of the bugs you had in the first version. I had one function, now I have 2 new types and 4 functions. Well, some defects were fixed which complicated the code a bit, but mostly I paid for functional decomposition.
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
c++, strings, search But that's fine. Splitting code into multiple functions usually makes it easier to read, more maintainable and more self-documenting. This is well worth the extra number of lines. The biggest increase in code size comes from calculateAdjacents(), and in particular to support the strong_repetition_count. I would focus on simplifying this function. Consider: size_t calculateAdjacents(const Index<>& index, std::vector<index_t>& adjacent_matches, size_t repetitions, bool strong_repetition_count) { return std::transform_reduce(/*std::execution::par_unseq,*/ index.begin(), index.end() - (repetitions - 1), size_t(0), std::ranges::max, [&](const auto& item) -> size_t { const auto& text = index.text; size_t idx = &item - std::data(index.index); size_t match_length = findMatchLengthWithOffsetInSuffixArray(index, idx, (repetitions - 1)); if (strong_repetition_count && !isStrongRepetition(match_length, …)) match_length = 0; } return adjacent_matches[idx] = match_length; }); } Sure, I moved the problem to isStrongRepetition(). But now that problem is compartmentalized and calculateAdjacents() looks reasonably simple again.
{ "domain": "codereview.stackexchange", "id": 45431, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, strings, search", "url": null }
java, database Title: which layer is more fit to check data integrity: service or database? Question: I read a book named Effective SQL and found this interesting part. Enforcing and maintaining business rules and relationships in the data is part of the data model, and the responsibility belongs to the database, not the application program. Data rules should be separated from the applications in order to ensure that everyone is working with the same data and that updates are done one way. Does this mean I should change below code ? private User googleSignup(UserDTO.GoogleUser googleUser) { userRepository.findByUsername(googleUser.getName()).ifPresent(user -> { throw new DuplicatedEntityException(ErrorCode.DUPLICATED_USERNAME); }); ... User user = User.ofSocial(googleUser.getName(), googleUser.getEmail()); return userRepository.save(user); } like this. Should I change to this code? (Data Integrity is already set up) private User googleSignup(UserDTO.GoogleUser googleUser) { User user = User.ofSocial(googleUser.getName(), googleUser.getEmail()); return userRepository.save(user); } With second code, calling DB count is reduced and the codes are simplified but I've never seen a code like this. Can you please share your opinion?
{ "domain": "codereview.stackexchange", "id": 45432, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, database", "url": null }
java, database Answer: You're essentially asking about CREATE UNIQUE INDEX, such as a table's PK, and how to interact with it. Firstly, in the system you describe there absolutely should be a UNIQUE key. Databases are very good at enforcing that kind of thing. What if there wasn't one, and the app tried to prevent dups using the OP code? Well, think about these two concurrent calls racing: googleSignup(alice); googleSignup(alice); Both of them get empty result from .findByUsername("alice"), then execute the ... part for a while, then both successfully .save(). That is, we suffered from a TOCTTOU bug, we INSERTed a pair of rows, and thereafter we'll never know which one to believe or to update when we see Alice again. So we need reliable arbitration at a foundational level. It could come from a mutex service that is global across all webserver instances, but an RDBMS would be most convenient here. Secondly, while the alternative piece of code seems more production ready, I do worry a little about the UX. It has a DuplicatedEntityException failure mode, which we don't specifically handle, so I imagine some generic user-unfriendly "unique key constraint" database message comes back to the user. The code is correct, but I anticipate a bug / enhancement request may be logged against it, if users encounter that frequently, find the response confusing, and complain about it. We might choose to catch the error, not because we're worried about corrupting another layer's bits, but because we wish to hold the user's hand, explain what happened, and suggest some new action the user might attempt in order to win on the second try.
{ "domain": "codereview.stackexchange", "id": 45432, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, database", "url": null }
java, performance, spring, jdbc, jpa Title: Inserting large number of rows into database with Spring boot Question: I need to insert many million rows + many GB of data into a database for a project that uses Spring boot. I recreated a minimal example with a one to many relationship and am trying to find the fastest solution. The full code is here: https://github.com/Vuizur/springmassinsert, but the rough structure is: // Email.java @Entity @Table(name = "emails") public class Email { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "address") private String address; @Column(name="text") private String text; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") private User user; } // User.java @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.LAZY) private List<Email> emails; } But the most important part is the insert code, where I tested 4 versions: @Service public class InsertService { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private UserRepository userRepository; private final int NUMBER_OF_USERS = 10000; private final int NUMBER_OF_EMAILS = 10;
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa private final int NUMBER_OF_USERS = 10000; private final int NUMBER_OF_EMAILS = 10; public void insert() { List<User> users = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { User user = new User(); user.setName("User " + i); List<Email> emails = new ArrayList<>(); for (int j = 0; j < NUMBER_OF_EMAILS; j++) { Email email = new Email(); email.setAddress("email" + j + "@gmail.com"); email.setUser(user); emails.add(email); } user.setEmails(emails); users.add(user); } userRepository.saveAll(users); } public void insertBatch() { List<User> users = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { User user = new User(); user.setName("User " + i); List<Email> emails = new ArrayList<>(); for (int j = 0; j < NUMBER_OF_EMAILS; j++) { Email email = new Email(); email.setAddress("email" + j + "@gmail.com"); email.setUser(user); emails.add(email); } user.setEmails(emails); users.add(user); if (i % 1000 == 0) { userRepository.saveAll(users); users.clear(); } } }
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa public void insertJdbc() { List<User> users = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { User user = new User(); user.setName("User " + i); List<Email> emails = new ArrayList<>(); for (int j = 0; j < NUMBER_OF_EMAILS; j++) { Email email = new Email(); email.setAddress("email" + j + "@gmail.com"); email.setUser(user); emails.add(email); } user.setEmails(emails); users.add(user); } for (User user : users) { jdbcTemplate.update("insert into users (name) values (?)", user.getName()); for (Email email : user.getEmails()) { jdbcTemplate.update("insert into emails (address, text, user_id) values (?, ?, ?)", email.getAddress(), email.getText(), user.getId()); } } }
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa public void insertJdbcBatch() { List<User> users = new ArrayList<>(); for (int i = 0; i < NUMBER_OF_USERS; i++) { User user = new User(); user.setName("User " + i); List<Email> emails = new ArrayList<>(); for (int j = 0; j < NUMBER_OF_EMAILS; j++) { Email email = new Email(); email.setAddress("email" + j + "@gmail.com"); email.setUser(user); emails.add(email); } user.setEmails(emails); users.add(user); } try { // Create a prepared statement for inserting users PreparedStatement userPs = jdbcTemplate.getDataSource().getConnection() .prepareStatement("insert into users (name) values (?)", Statement.RETURN_GENERATED_KEYS); // Create a prepared statement for inserting emails PreparedStatement emailPs = jdbcTemplate.getDataSource().getConnection() .prepareStatement("insert into emails (address, text, user_id) values (?, ?, ?)"); for (User user : users) { // Set the user name parameter and add to the batch userPs.setString(1, user.getName()); userPs.addBatch(); } // Execute the batch update for users and get the generated ids userPs.executeBatch(); ResultSet rs = userPs.getGeneratedKeys(); int index = 0; while (rs.next()) { // Set the user id from the result set users.get(index).setId(rs.getLong(1)); index++; } for (User user : users) { for (Email email : user.getEmails()) { // Set the email parameters and add to the batch emailPs.setString(1, email.getAddress()); emailPs.setString(2, email.getText());
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa emailPs.setString(2, email.getText()); emailPs.setLong(3, user.getId()); emailPs.addBatch(); } } // Execute the batch update for emails emailPs.executeBatch(); } catch (Exception e) { System.out.println(e); }
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa } @PostConstruct public void benchmark() { long startTime = System.currentTimeMillis(); insertJdbcBatch(); long endTime = System.currentTimeMillis(); System.out.println("Inserting " + NUMBER_OF_USERS + " users with " + NUMBER_OF_EMAILS + " emails each took " + (endTime - startTime) + " milliseconds"); // Print insert per seconds System.out .println((NUMBER_OF_USERS * NUMBER_OF_EMAILS * 1.0 / ((endTime - startTime) / 1000.0)) + " inserts per second"); } } The performance results are (on a bad external HDD): Approach Inserts/second JPA (insert) 4247 JPA with save all 1000 4401 JDBC 1842 JDBC with prepared statements 13005 So the difference between the first two versions is not significant, the naive JDBC version is really slow, but JDBC with prepared statements is the clear winner. Is there something else I can do to speed up the inserts even more?
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa Answer: It makes sense to me that JDBC with prepared statements would win that contest, as we don't have to keep re-parsing the same old SQL command. Batch size before COMMIT tends to be pretty important. Increase it from "1 row at a time", which gives terrible throughput, to ten rows, a hundred, a thousand, maybe ten thousand. At some point you'll see that rows-per-second throughput stops increasing, remains stable as you bump up the batch size, and then actually goes down as your giant batches become counter productive. When sending across a TCP connection to a DB server, we want to be sending enough data that TCP gets to open the congestion window and send at full tilt. When storing to Winchester media, we want to send enough to keep the track buffer full, so it will write for a full spin, seek to adjacent track, and keep writing. With TCP the big batches hide end-to-end packet latency, and with HDD they hide track seek latency. (The effect is less pronounced with SSD, though still quite noticeable.) Rule of thumb: we want to send batches that will keep the underlying storage subsystem busy with about 500 msec to 5 seconds worth of work. Sending a batch of just 10 msec of work tends to expose latency issues, and sending a batch that will take many seconds to flush out to stable storage is counterproductive because it uselessly fills RAM, messing with our buffer eviction strategy. The other thing you can look at is you might choose to make your "upload the rows" operation as simple as possible. In particular, verifying constraints like UNIQUE, FOREIGN KEY, and even just producing several indexes on different columns, can induce random read I/Os. What we want is sequential I/O, with hardly any seeking. So one strategy, which at a minimum lets you break apart aggregate timings into per-system components, is to INSERT the rows into a scratch_user table, something like that. Be sure to COMMIT every couple of seconds.
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
java, performance, spring, jdbc, jpa something like that. Be sure to COMMIT every couple of seconds. As a separate operation, do a giant INSERT ... SELECT FROM scratch_user, as a single transaction with explicit COMMIT at the end. This makes network effects disappear from the second transaction, and gives the query planner more flexibility to choose a good plan which involves sorting, enforcing uniqueness, and maybe table scanning for FK checks. Tacking on an ORDER BY will sometimes result in fuller table blocks, that is, with no randomly ordered INSERTs there was no need for B-tree page splits. But now we're getting into more subtle aspects. set expectations You reported write throughput of 13,000 rows/second, using single DB server and single disk drive. What read throughput could you obtain? (Stop the database, unmount its filesystem, remount, restart, so you're not cheating w.r.t. cache hits when you make timing measurements.) You probably can't pull much more than 90,000 rows/second out of single server + single drive, right? You can always scale out. Attach multiple drives, preferably as multiple tablespaces so the backend query planner can "see" what I/O resources are available. Double the number of cores on your DB server, if measurements show that you're CPU bound (often you won't be -- commonly it's I/O bound). Add more servers to your database cluster (though this tends to win more for concurrent reading than writing). Rent resources from a cloud vendor, so scale-out is limited only by your wallet. Your write rate will never exceed your read rate, especially if we scribble each row into a transaction journal and into the destination table. So use "fastest SELECT time" to set reasonable expectations on what your equipment could possibly do, and don't deceive yourself by letting cache hits look like they're measuring disk read rates.
{ "domain": "codereview.stackexchange", "id": 45433, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, performance, spring, jdbc, jpa", "url": null }
r Title: Correctness of newborn feeding data visualization Question: Just wanted some code review for correctness here. This is a little app for plotting newborn feeding data (important to keep track of in the first 48 hours of so) that I hope to provide to a clinic, but I wanted some extra eyes on it if possible before doing so (important to get this right!). We have the times of the feeds in military time given for today and yesterday, where the newborn was born yesterday. I show a visualization in a sense to prove the code is correct to the viewer. today = c("0800", "0645", "0300","0200") yesterday = c("2400", "2225", "2045") yesterdaylabels = lapply(yesterday,function(x){paste0("Yesterday ",x)}) todaylabels = lapply(today,function(x){paste0("Today ",x)}) dayslabels = c(rev(yesterdaylabels),rev(todaylabels)) #yesterday = c("2045", "2225", "2400") #today = c("0200", "0400", "0645","0800") yesterday = rev(yesterday) today = rev(today) days = list(yesterday,today) check.day = function(day){ lapply(day,function(x){ if(nchar(x)==4){ print("ok") }else{ print("One of the times doesn't have 4 digits! Stopping.") break } }) } for (day in days){check.day(day)} get.day.in.min = function(day){ get.first.two = function(x){lapply(day,function(x){substr(x,1,2)})} get.last.two = function(x){lapply(day,function(x){substr(x,3,4)})} day.hours = as.numeric(get.first.two(day)) day.minutes = as.numeric(get.last.two(day)) day.in.minutes = day.hours*60 + day.minutes day.in.minutes } alldays = c() for (day.ix in 1:length(days)){ newday = get.day.in.min(days[[day.ix]])+24*60*(day.ix-1) alldays = c(alldays,newday) } ntimes = length(alldays) timeix=rep(0,ntimes) daysoffset= c(alldays[2:length(alldays)],NaN) #today = c() timebtwnhrs = (daysoffset-alldays)/60
{ "domain": "codereview.stackexchange", "id": 45434, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r", "url": null }
r daysoffset= c(alldays[2:length(alldays)],NaN) #today = c() timebtwnhrs = (daysoffset-alldays)/60 range = round(c(min(timebtwnhrs,na.rm=TRUE),max(timebtwnhrs,na.rm=TRUE)),1) plot(alldays,timeix, pch=20, #pch=3, #xlab=paste0("Minutes \n Hours between feeds: mean = ", round(mean(timebtwnhrs,na.rm=TRUE),1)," (min = ",range[1],", max = ",range[2],")"), xlab=paste0("Hours between feeds: mean (range): ", round(mean(timebtwnhrs,na.rm=TRUE),1)," (min = ",range[1],", max = ",range[2],")"), xaxt="n", yaxt='n',ylab="",frame.plot = FALSE,ylim=c(0,3)) for (i in 1:length(alldays)){ text(x=alldays[i],y=0.5, labels=dayslabels[[i]],srt=-90) } Answer: If by correctness you mean that it does what it says it does, then, yes, it does. I don't see any reasonable cases where this would give incorrect results
{ "domain": "codereview.stackexchange", "id": 45434, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r", "url": null }
c++, array, iterator, collections, vectors Title: A dynamic array with an iterator compatible with std::sort Question: I wrote a Vector (dynamic array) class with an iterator usable with std::sort() . It seems to pass my tests. I wondering about the issues one can spot on this implementation. I compiled with C++17. #include <iostream> #include <numeric> using std::cout, std::endl; template<typename T> struct Vector { struct Iterator { using value_type = T; using difference_type = std::ptrdiff_t; using pointer = T*; using reference = T&; using iterator_category = std::random_access_iterator_tag; Iterator(value_type* ptr) : m_ptr(ptr) {} value_type& operator*() { return *m_ptr; } Iterator& operator--() { m_ptr--; return *this; } Iterator& operator++() { m_ptr++; return *this; } Iterator& operator++(int) { Iterator it = *this; ++(*this); return it; } bool operator==(const Iterator& other) const { return m_ptr == other.m_ptr; } bool operator!=(const Iterator& other) const { return !(*this == other); } bool operator<(const Iterator& other) const { return *m_ptr < *other.m_ptr; } bool operator>(const Iterator& other) const { return *m_ptr > *other.m_ptr; } bool operator>=(const Iterator& other) const { return *m_ptr >= *other.m_ptr; } Iterator operator+(const size_t n) const { Iterator it = *this; it.m_ptr += n; return it; } Iterator operator-(const size_t n) const { Iterator it = *this; it.m_ptr -= n; return it; }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors size_t operator-(const Iterator& other) const { return m_ptr - other.m_ptr; } Iterator operator-=(const size_t n) const { Iterator it = *this; it.m_ptr -= n; return it; } Iterator operator+=(const size_t n) const { Iterator it = *this; it.m_ptr += n; return it; } private: value_type* m_ptr; }; void allocate(size_t capacity) { capacity += m_capacity; T* data = new T[capacity]; std::copy_n(m_data, m_capacity, data); m_capacity = capacity; delete[] m_data; m_data = data; } void push_back(T value) { if (!(m_index < m_capacity)) allocate(3); m_data[m_index++] = value; } T& operator[](size_t index) { return m_data[index]; } size_t size() { return m_index; } size_t capacity() { return m_capacity; } Iterator begin() { return Iterator(m_data); } Iterator end() { return Iterator(m_data + m_index); } private: size_t m_index = 0; size_t m_capacity = 0; T* m_data = nullptr; }; void test() { int A[] = {2,7,9,1,7}; Vector<int> V1; cout << "size of A " << std::size(A) << endl; for (size_t i = 0; i < std::size(A); ++i) V1.push_back(A[i]); for (size_t i = 0; i < V1.size(); ++i) cout << V1[i] << endl; cout << "V capacity is " << V1.capacity() << endl; Vector<int>::Iterator beg = V1.begin(); Vector<int>::Iterator end = V1.end(); cout << "beg is " << *beg << endl; cout << "end is " << *end << endl; for (const auto& v : V1) cout << v << endl; if (beg < end) cout << "<" << endl; std::vector<int> v1 {2,7,9,1,7}; std::vector<int>::iterator beg1 = v1.begin(); std::vector<int>::iterator end1 = v1.end();
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors cout << "-n " << *(end-1) << endl; cout << "+n " << *(beg+1) << endl; cout << " - " << end-beg << endl; cout << *(end -= 2) << endl; std::sort(V1.begin(), V1.end()); for (auto& v : V1) cout << v << endl; } int main() { cout << "starting... " << endl; test(); }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors Answer: Before I get into the review, I need to offer some advice. std::vector is a type of dynamic array, but not the only type. The thing that makes std::vector special is that it has extra capacity. You can reserve space in a vector, and fill that space in later with actual objects. That is handy for minimizing the number of allocations, and controlling when those allocations happen. The cost is a massive increase in complexity, and almost doubling the size needed for the type. A simple dynamic array, on the other hand, does not have extra capacity. That means that every time you push another object into the array, it needs to reallocate and shuffle stuff around. On the other hand, such a dynamic array is much simpler, and the type itself only needs to store a pointer and a size. If you are trying to remake std::vector, my advice to you is: don’t. It is hard. It is stupidly hard. I have seen literally hundreds of coders attempt it, and fail—and I mean “literally” quite literally; just do a search for vector re-implementation here at CodeReview, and you will see thousands of results, and almost all of them are wrong. Beginners frequently fall for the trap of thinking that because std::vector is easy to understand and use, then it must be easy to implement… but it is not. It may be the hardest thing in the entire standard library to implement. Yes, it is way harder to implement than std::string, std::map, std::thread, std::shared_ptr, and anything in the IOstreams library. Just about the only things in C++20 that are harder might be std::regex and some of the floating point conversion stuff. Beginners also assume that if they do manage to figure out how to re-implement std::vector correctly, they will have learned a lot of useful C++. False. Most of the knowledge you need to correctly re-implement std::vector is useful only for re-implementing std::vector (or similar types), and does not provide any useful skills you can translate to any other problem domain.
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors So to summarize:
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors Re-implementing std::vector is a lot harder than you think it is. You will get it wrong. I say this with almost 100% certainty. You will not learn anything useful from the attempt. Now, if you just want to make a simple dynamic array… that is a good learning project. And, it is useful. A simple dynamic array is a very useful type; sometimes std::vector is just too heavyweight. I have a simple dynamic array in my own personal code library, and I use it often. (Granted, my simply dynamic array is not that simple at all; it optimizes for small types and small allocations, and has a bunch of other nifty features which make it technically closer to std::vector than not… but it is still simpler than std::vector.) So my advice is: Don’t try to re-implement std::vector. Make a simple dynamic array. What you have right now is basically a simple dynamic array. This is good. Make it a good simply dynamic array, and you will gain both a good C++ learning experience, and a type you can actually use. In particular, drop the idea of “capacity”, and ignore any advice that involves having a capacity that is not equal to the size. Just make a good, simple dynamic array. Now, onto the code review. You mentioned you are using C++17, but the current version is C++20… and, the actual current version is C++23, but the final approval was delayed (a knock-on effect from COVID), so although C++23 is finished, it is not actually formally published yet. In any case, you should upgrade at least to C++20. C++17 is already starting to become archaic. Whenever you are making a thing—a type, a function, whatever—that seems like it might be useful, you should either: put it in a dedicated header file; or if you have access to more modern tools, put it in a module.
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors put it in a dedicated header file; or if you have access to more modern tools, put it in a module. You should also put everything you make in your own namespace. You should avoid putting anything in the global namespace as much as possible. So, assuming you are still using headers, your code should look something like this: #ifndef KCFNMI_INCLUDE_GUARD_VECTOR #define KCFNMI_INCLUDE_GUARD_VECTOR // any includes you need go here namespace kcfnmi { template <typename T> struct Vector { // ... [snip] ... }; } // namespace kcfnmi #endif // include guard And that should be in a file kcfnmi/vector.hpp, or something like that. Then your test program would be: #include <iostream> // any other includes you need for testing #include <kcfnmi/vector.hpp> // not a fan of doing this, but if you really want: using std::cout, std::endl; // again, if you really want: using kcfnmi::Vector; void test() { // ... [snip] ... } auto main() -> int { cout << "starting... " << endl; test(); } But you should really look into using a proper unit testing framework. #include <iostream> #include <numeric> You only need <iostream> for testing, and I can’t figure out why you need <numeric> at all. On the flip side, you use std::ptrdiff_t and std::size_t, but you don’t include <cstddef>. You use std::random_access_iterator_tag, but don’t include <iterator>. And you use std::copy_n, but don’t include <algorithm>. template<typename T> struct Vector
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors The convention in C++ is to use class if a type has an invariant. Your class does have an invariant; several actually. One is that m_capacity must always be greater than or equal to m_index. Another is that if m_data is not nullptr, then m_index (and/or) m_capacity must be equal to the number of elements in the array pointed to by m_data. Another way of stating the same convention is if a type has any private members you should use class, not struct. Your type has private members, therefore it should be a class, not a struct. Something you should look into is constraining T. Right now, as the type is written, you can use anything as T, even things that make no sense. When you do use something silly, you will either get bizarre and long-winded compile errors, or, worse, strange bugs. For example, right now I could make a Vector of references, or functions, or even Vector<void>. None of those make any sense (and will probably not compile, depending on a number of factors). Exactly how you want to constrain T is up to you. I’d suggest a good starting point is std::semiregular (actually, a good starting point is always std::regular, but that includes comparisons, and we don’t need that, so, std::semiregular). So: template <std::semiregular T> struct Vector // or, equivalently template <typename T> requires std::semiregular<T> struct Vector Prior to C++20, you could still constrain the type, but it’s more complicated and less useful. Just move to C++20. struct Iterator { So, here’s where I point out that your vector has no concept of const-correctness. To see what I mean, just try passing an instance of your vector through a const&, and try… well… anything: auto test_1(Vector<int> const& v) { // Can't even get the size! std::cout << v.size(); } auto test() { Vector<int> v; test_1(v); }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors auto test() { Vector<int> v; test_1(v); } The hardest part of container const-correctness is getting the iterators right. A common mistake people make is assuming that const_iterator is the same thing as const iterator. I’ve even seen blog points by purported C++ “experts” get that wrong. The canonical way to make an iterator for a container is to make a base template with a bool template parameter that controls whether the iterator is const or not: template <typename T> class Vector { private: template <bool Const> class _iterator { public: using value_type = std::remove_cv_t<T>; using pointer = std::conditional_t<Const, T const*, T*>; using reference = std::conditional_t<Const, T const&, T&>; // ... etc. }; public: using iterator = _iterator<false>; using const_iterator = _iterator<true>; // ... etc. It’s a little more complicated than that (you have to take into account implicit conversions from iterator to const_iterator), but that’s the basic idea. using iterator_category = std::random_access_iterator_tag; This is fine, but C++20 introduced the contiguous iterator concept, which can net you huge performance gains. The way to use that is: using iterator_category = std::random_access_iterator_tag; using iterator_concept = std::contiguous_iterator_tag; That is, you shouldn’t set iterator_category to std::contiguous_iterator_tag, but rather use iterator_concept instead. (The reasons for why have to do with backward compatibility with crappily-written code, and are not worth going into.) However… and here I have to pour a bit a cold water on your implementation… starting in C++20, there is a very easy way to test whether you’ve got an iterator done correctly. All you need to do is check with one of the iterator concepts. Unfortunately…: auto main() -> int { using iter = Vector<int>::Iterator;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors std::cout.setf(std::ios_base::boolalpha); std::cout << "indirectly readable: " << std::indirectly_readable<iter> << '\n'; std::cout << "input-or-output iterator: " << std::input_or_output_iterator<iter> << '\n'; std::cout << "input iterator: " << std::input_iterator<iter> << '\n'; std::cout << "forward iterator: " << std::forward_iterator<iter> << '\n'; std::cout << "bidirectional iterator: " << std::bidirectional_iterator<iter> << '\n'; std::cout << "random access iterator: " << std::random_access_iterator<iter> << '\n'; std::cout << "contiguous iterator: " << std::contiguous_iterator<iter> << '\n'; } … produces…: indirectly readable: false input-or-output iterator: true input iterator: false forward iterator: false bidirectional iterator: false random access iterator: false contiguous iterator: false See here for the actual results. In other words, your iterator fails almost every test. A large part of the reason for this failing is the lack of const-correctness. When std::indirectly_readable checks operator*, it does so for a const iterator. But your operator* is not const qualified, so it fails. Simply adding const qualification to operator* makes it pass std::indirectly_readable… which immediately also makes it a valid std::input_iterator as well. Of course, there’s a long way to go from there to a valid random-access iterator (let alone a valid contiguous iterator). (For example, I think the reason it’s failing the forward iterator test has to do with the dangling reference bug @Deduplicator mentioned.) But it’s a start. Iterator(value_type* ptr) : m_ptr(ptr) {}
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors This should not be a public constructor, and it absolutely should not be an implicit converting constructor. The way the iterator is written now, any T* can be implicitly converted to a Vector<T>::Iterator. That’s bad, because any random pointer is not likely to be a valid iterator value. This constructor should be private, and the vector class should be a friend to access that constructor. (There are other tricks you could use, but this is the simplest.) Also, the constructor should be explicit. And constexpr, and noexcept as well. In general, you could use constexpr pretty much everywhere. noexcept should only be used if a function/constructor/operator/whatever can never fail under any circumstance. This constructor should never fail. You also need a public default constructor. It’s fine if it just sets m_ptr to nullptr. (It doesn’t matter what it sets m_ptr to, because no-one should ever dereference or do anything with a default-constructed iterator.) The default constructor should also be constexpr and noexcept. value_type& operator*() { return *m_ptr; } This is mostly fine (but should be constexpr… but not noexcept, because it will fail if m_ptr is nullptr, or when it points to past-the-end). However, it should return reference, not value_type&. It should also be const qualified. You are missing operator->, though. Iterator& operator--() You’re missing suffix operator--. bool operator==(const Iterator& other) const { return m_ptr == other.m_ptr; } As @Deduplicator mentioned, the modern way to do this is: constexpr auto operator<=>(Iterator const&) const noexcept = default;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors This will eliminate the need for operator!= and all the ordering operators… which, by the way…: bool operator<(const Iterator& other) const { return *m_ptr < *other.m_ptr; } bool operator>(const Iterator& other) const { return *m_ptr > *other.m_ptr; } bool operator>=(const Iterator& other) const { return *m_ptr >= *other.m_ptr; } These are all wrong. You should not be de-referencing the pointers before comparing them. And you’re missing operator<=. But it would be better to throw all these out and just use a defaulted operator<=>. Iterator operator+(const size_t n) const { Iterator it = *this; it.m_ptr += n; return it; } It’s std::size_t. The std:: is not optional, but for historical reasons, most compilers allow it… for now. That will change soon. But, in fact, std::size_t is not the right type to use here. You should be using the difference_type… which is std::ptrdiff_t, but you should just use difference_type. This is true for all of the random-access operations. Also, while you support it + n, you don’t support n + it. So that’s it for the iterator. Now into the guts of the actual container. void allocate(size_t capacity) { capacity += m_capacity; T* data = new T[capacity]; std::copy_n(m_data, m_capacity, data); m_capacity = capacity; delete[] m_data; m_data = data; }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors m_capacity = capacity; delete[] m_data; m_data = data; } This really shouldn’t be a public function at all. There is no reason to give the the world this kind of access. If a user wants to add more objects, let them push_back() (or emplace_back()) one or append_range() several. Now, consider this… after you grow the space with new T[capacity], you copy the existing objects into the new array. This is not great, because copying is usually expensive, and likely to throw. What you want to do is move, because moving is usually faster, and often no-fail. However… if moving can fail, you don’t want to do that. To understand why, imaging there are 10 elements in the container. You are adding 1 more. So you allocate a new array with 11 spaces, and then start to move/copy the 10 elements into it. But then, after 5 elements, there is a failure! If you had copied the elements, then no problem… just delete the new array, and the old data is untouched. Buf if you had moved the elements, then the 5 elements that were already moved have been messed up. This is actually such a critical concern that the standard library has a function for it: std::move_if_noexcept(). This will do the correct thing: move if it’s safe, and copy if it’s not. So: auto allocate(std::size_t capacity) { capacity += m_capacity; // USE SMART POINTERS!!! auto data = std::make_unique<T[]>(capacity); for (auto i = std::size_t{}; i < m_capacity; ++i) data[i] = std::move_if_noexcept(m_data[i]); auto p = data.release(); data.reset(m_data); m_data = p; m_capacity = capacity; } Unfortunately, it means you have to write a manual loop, which is not great. There are ways you can do it better, but this will do. void push_back(T value) { if (!(m_index < m_capacity)) allocate(3); m_data[m_index++] = value; }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors m_data[m_index++] = value; } You are making unnecessary copies. At the very least you should move in the last line. Now, here is where I get back to what I talked about in the beginning. Forget having extra capacity. Drop m_capacity completely, and just keep track of the size with m_index (which should probably be named m_size). Don’t bother to allocate 3 extra spaces, or double the space, or any such nonsense. Just add one extra space, and move the provided value into it. And consider what happens if moving that value fails. You need to clean up after yourself. So the function should be: auto push_back(T value) { // Allocate the new space. // // If this fails, no problem; we haven't touched anything yet. auto data = std::make_unique<T[]>(m_index + 1); // Copy/move the new value in. // // If this fails, no problem; we haven't touched anything yet. data[m_index] = std::move(value); // Copy/move the existing values in. // // If anything here fails, we were copying (because we won't move if // moving could fail), so no big deal. The original data is still // intact. for (auto i = std::size_t{}; i < m_capacity; ++i) data[i] = std::move_if_noexcept(m_data[i]); // Now all the data is where we want it in the new space. // Let's replace the old data with the new data. auto p = data.release(); data.reset(m_data); m_data = p; // And increment the size. ++m_index; // The old data is cleaned up automatically. } If you want to break the re-allocation into its own function, you need to keep in mind the order stuff has to happen. T& operator[](size_t index) { return m_data[index]; } This is fine (except it should be std::size_t, but you also need a const qualified version. size_t size() { return m_index; }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors This should be const qualified, and noexcept (and constexpr, of course). Also, you should consider that containers require a few standard types to be defined. A container needs value_type (which is just T), but it also needs: reference const_reference iterator const_iterator difference_type size_type (Also, reverse_iterator and const_reverse_iterator for any container with bidirectional iterators or better.) size_type can be defined as std::size_t, but you should use that instead of std::size_t in places like the return type of size(). size_t capacity() { return m_capacity; } As I mentioned; drop this. Just let the capacity always be the size. Iterator begin() { return Iterator(m_data); } Iterator end() { return Iterator(m_data + m_index); } These should be const qualified and noexcept (and, as always, constexpr). However, there is a little wrinkle in that you should have a non-const begin() that returns iterator and a const begin() that returns const_iterator (and also a cbegin() that returns const_iterator). Same for end(). (You should also have rbegin() and rend() in const and non-const flavours, and crbegin() and crend().) I mentioned above some of the things you need to make your iterator a proper iterator (not to mention a proper random-access or contiguous iterator), and a way to test that you’re compliant. Unfortunately there’s no such easy test for containers. I would say for a dynamic array, your interface should be something like: template <typename T> class Vector { public: // Types =========================================================== using value_type = /*...*/; using reference = /*...*/; using const_reference = /*...*/; using iterator = /*...*/; using const_iterator = /*...*/; using reverse_iterator = /*...*/; using const_reverse_iterator = /*...*/; using difference_type = /*...*/; using size_type = /*...*/;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors using difference_type = /*...*/; using size_type = /*...*/; // Default initializable =========================================== // Should be no-fail. constexpr Vector() noexcept; // Copyable ======================================================== constexpr Vector(Vector const&); constexpr auto operator=(Vector const&) -> Vector&; // Copyable ======================================================== // Should be no-fail. constexpr Vector(Vector&&) noexcept; constexpr auto operator=(Vector&&) noexcept -> Vector&; // Other construction ============================================== constexpr Vector(size_type, value_type const&); template <std::input_iterator I, std::sentinel_for<I> S> constexpr Vector(I, S); // From C++23: template <std::ranges::input_range R> constexpr Vector(std::from_range_t, R&&); constexpr Vector(std::initializer_list<value_type>); // Destruction ===================================================== constexpr ~Vector(); // Querying size =================================================== constexpr auto empty() const noexcept -> bool; constexpr auto size() const noexcept -> size_type; constexpr auto max_size() const noexcept -> size_type; // Iterators ======================================================= constexpr auto begin() noexcept -> iterator; constexpr auto begin() const noexcept -> const_iterator; constexpr auto end() noexcept -> iterator; constexpr auto end() const noexcept -> const_iterator; constexpr auto cbegin() const noexcept -> const_iterator; constexpr auto cend() const noexcept -> const_iterator;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors constexpr auto rbegin() noexcept -> reverse_iterator; constexpr auto rbegin() const noexcept -> const_reverse_iterator; constexpr auto rend() noexcept -> reverse_iterator; constexpr auto rend() const noexcept -> const_reverse_iterator; constexpr auto crbegin() const noexcept -> const_reverse_iterator; constexpr auto crend() const noexcept -> const_reverse_iterator; // Swap ============================================================ // Should be no-fail. constexpr auto swap(Vector&) noexcept -> void; friend constexpr auto swap(Vector&, Vector&) noexcept -> void; // Comparison ====================================================== constexpr auto operator==(Vector const&) noexcept const -> bool; // operator!= is automatic as of C++20. // Assignment from initializer list ================================ constexpr auto operator=(std::initializer_list<value_type>) -> Vector&; // Emplacement ===================================================== template <typename... Args> constexpr auto emplace(const_iterator, Args&&...) -> iterator; // Assignment ====================================================== constexpr auto assign(size_type, value_type const&) -> void; template <std::input_iterator I, std::sentinel_for<I> S> constexpr auto assign(I, S) -> void; constexpr auto assign(std::initializer_list<value_type>) -> void; // From C++23: template <std::ranges::input_range R> constexpr auto assign_range(R&&) -> void;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors // Insertion ======================================================= constexpr auto insert(const_iterator, value_type const&) -> iterator; constexpr auto insert(const_iterator, value_type&&) -> iterator; constexpr auto insert(const_iterator, size_type, value_type const&) -> iterator; template <std::input_iterator I, std::sentinel_for<I> S> constexpr auto insert(const_iterator, I, S) -> iterator; constexpr auto insert(const_iterator, std::initializer_list<value_type>) -> iterator; // From C++23: template <std::ranges::input_range R> constexpr auto insert_range(const_iterator, R&&) -> iterator; // Erasure ========================================================= constexpr auto erase(const_iterator) -> iterator; constexpr auto erase(const_iterator, const_iterator) -> iterator; // Clear =========================================================== // Should be no-fail. constexpr auto clear() noexcept -> void; // ***************************************************************** // All of the above are REQUIRED for a standard sequence container // with contiguous storage. // // Everything below is optional. // ***************************************************************** // Element access ================================================== constexpr auto operator[](size_type) -> reference; constexpr auto operator[](size_type) const -> const_reference; constexpr auto at(size_type) -> reference; constexpr auto at(size_type) const -> const_reference; constexpr auto front() -> reference; constexpr auto front() const -> const_reference; constexpr auto back() -> reference; constexpr auto back() const -> const_reference; // Front operations ================================================ template <typename... Args> constexpr auto emplace_front(Args&&...) -> void;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors constexpr auto push_front(value_type const&) -> void; constexpr auto push_front(value_type&&) -> void; template <std::ranges::input_range R> constexpr auto prepend_range(R&&) -> void; constexpr auto pop_front() -> void; // Back operations ================================================= template <typename... Args> constexpr auto emplace_back(Args&&...) -> void; constexpr auto push_back(value_type const&) -> void; constexpr auto push_back(value_type&&) -> void; template <std::ranges::input_range R> constexpr auto append_range(R&&) -> void; constexpr auto pop_back() -> void; // Contiguous data access ========================================== constexpr auto data() -> value_type*; constexpr auto data() const -> value_type const*; // Resizing ======================================================== constexpr auto resize(size_type) -> void; constexpr auto resize(size_type, value_type const&) -> void; // Erasure ========================================================= template <typename U> friend auto erase(Vector&, U const&) -> size_type; template <typename Pred> friend auto erase_if(Vector&, Pred) -> size_type; }; template <std::input_iterator I, std::sentinel_for<I> S> Vector(I, S) -> Vector<typename std::iterator_traits<I>::value_type>; // From C++23: template <std::ranges::input_range R> Vector(std::from_range_t, R&&) -> Vector<std::ranges::range_value_t<R>>; Which, as you can see, is a lot. But it’s not as bad as it seems, because there are really only a handful of functions that are fundamental, then most other functions can be implemented in terms of them. For example, if you implement: template <typename... Args> constexpr auto emplace(const_iterator, Args&&...) -> iterator;
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors Then all the following are just in terms of that: // Insertion ======================================================= constexpr auto insert(const_iterator p, value_type const& v) -> iterator { return emplace(p, v); } constexpr auto insert(const_iterator p, value_type&& v) -> iterator { return emplace(p, std::move(v)); } constexpr auto insert(const_iterator p, size_type n, value_type const& v) -> iterator { auto const pos = p - begin(); for (size_type i = 0; i < n; ++i) p = std::next(emplace(p, v)); return begin() + pos; } template <std::input_iterator I, std::sentinel_for<I> S> constexpr auto insert(const_iterator p, I first, S last) -> iterator { auto const pos = p - begin(); while (first != last) p = std::next(emplace(p, *first++)); return begin() + pos; } constexpr auto insert(const_iterator p, std::initializer_list<value_type> il) -> iterator { return insert(p, il.begin(), il.end()); } // From C++23: template <std::ranges::input_range R> constexpr auto insert_range(const_iterator p, R&& r) -> iterator { return insert(std::ranges::begin(r), std::ranges::end(r)); } // Front operations ================================================ template <typename... Args> constexpr auto emplace_front(Args&&... args) -> void { emplace(begin(), std::forward<Args>(args)...); } constexpr auto push_front(value_type const& v) -> void { emplace(begin(), v); } constexpr auto push_front(value_type&& v) -> void { emplace(begin(), std::move(v)); } template <std::ranges::input_range R> constexpr auto prepend_range(R&& r) -> void { insert(begin(), std::forward<R>(r)); } // Back operations ================================================= template <typename... Args> constexpr auto emplace_back(Args&&...) -> void { emplace(end(), std::forward<Args>(args)...); } constexpr auto push_back(value_type const&) -> void { emplace(end(), v); }
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
c++, array, iterator, collections, vectors constexpr auto push_back(value_type const&) -> void { emplace(end(), v); } constexpr auto push_back(value_type&&) -> void { emplace(end(), std::move(v)); } template <std::ranges::input_range R> constexpr auto append_range(R&& r) -> void { insert(end(), std::forward<R>(r)); } And there’s more. Assigns are just clear() then insert(begin(), ...). These won’t necessarily be the most efficient implementations, but you can make them work first, then make them fast. The really important stuff that you are missing are the copy/move operations, and the destructor. I’m actually shocked that no-one has pointed that out yet, because your class is a faucet for leaking memory. You need at least a destructor to free up all the memory allocated, and as soon as you add a destructor, you also need copy and move operations to properly shuffle the managed memory around. That’s all! In summary: Don’t try to re-implement std::vector. Don’t bother with extra capacity, growth strategies, or any of that nonsense. That stuff is stupendously hard to implement correctly, and not worth the effort of learning. Move to C++20, at least. C++17 is already archaic. Look up the standard requirements for iterators and containers, and try to match them. At the very least, add a destructor to free up the allocated memory, and copy/move operations to manage it properly.
{ "domain": "codereview.stackexchange", "id": 45435, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, array, iterator, collections, vectors", "url": null }
php, ruby, ruby-on-rails Title: Rails session after migrate from PHP (improved) Question: previusly I make a post for Session Logic for User Verification in Rails Migration. Now the improvement version following advice of the comments is here. The problem was the use of `` for executing in shell on a RoR application when making the log in. I remove it and change for system method. module Shared extend ActiveSupport::Concern def password_regex / \A # The string must (?=.*[a-z]) # contain at least 1 lowercase alphabetical character (?=.*[A-Z]) # contain at least 1 uppercase alphabetical character (?=.*[0-9]) # contain at least 1 numeric character (?=.*[!@#$%^&*]) # contain at least one special character .{8,} # Be eight characters or longer \z /x end end class SessionsController < ApplicationController include Shared layout 'modal-wrapper' def new @user = User.new end def create @user = User.find_by(username: username) if valid_params?(password) session[:user_id] = @user.id redirect_to root_path else flash[:error] = 'Invalid user or password.' redirect_to login_path end end private def legacy_authenticate(pass_plain) php_file = 'app/scripts/legacy_authenticate.php' if pass_plain =~ password_regex system('php', php_file, pass_plain, @user.password_php) else false end end def valid_params?(pass_plain) if @user&.password_php legacy_authenticate(pass_plain) elsif @user&.password_digest @user.authenticate(pass_plain) else false end end def username params[:user][:username] end def password params[:user][:password] end end legacy_authenticate.php $password = $argv[1]; $hased_password = $argv[2]; if (password_verify($password, $hased_password)) { exit(0); } else { exit(1); }
{ "domain": "codereview.stackexchange", "id": 45436, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, ruby, ruby-on-rails", "url": null }
php, ruby, ruby-on-rails if (password_verify($password, $hased_password)) { exit(0); } else { exit(1); } the form that call the method <%= form_for(@user, html: { class: 'log-form' }) do |f| %> <%= f.text_field :firstname, placeholder: 'First Name' %> <%= f.text_field :lastname, placeholder: 'Last Name' %> <%= f.text_field :username, placeholder: 'Username', required: true %> <%= f.email_field :email, placeholder: 'Email', required: true %> <%= f.password_field :password, placeholder: 'Password', required: true %> <%= f.password_field :password_confirmation, placeholder: 'Confirm Password', required: true %> <%= f.submit 'Log Up', class: 'btn btn-submit' %> <% end %> the unit test with 0 failures require 'test_helper' class SessionsControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:one) end test 'should get new' do get login_path assert_response :success end test 'should login' do post login_path, params: { user: { username: @user.username, password: 'MyString#123' } } assert_response :redirect assert_redirected_to root_path end test 'should logout' do delete logout_path assert_response :redirect assert_redirected_to root_path end end and the tested data yml file one: username: MyString email: MyString@MyString.com password_php: $2y$10$FYJ5PvFRPaFWWZPhFYlxEuiETZwlk5PmoehlOiR93r3.4M3gU8QVy password_digest: <%= BCrypt::Password.create('MyString#123') %> Fell free to check the other post, all the modification were following the advice of J_H including the writing of this post Answer: Regarding the PHP part, you can make it a bit simpler $result = password_verify($password, $hased_password); exit((int)$result);
{ "domain": "codereview.stackexchange", "id": 45436, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, ruby, ruby-on-rails", "url": null }
beginner, c, homework, binary-tree Title: Binary tree struct in C Question: Its been done to death, but the particular prompt (see Assignment 4) guiding me has strict+simple requirements that lead to a nice reduced environment to critique poor form. The project implements a heap-based binary tree structure with insert, find, and remove functions. Both the binary tree nodes' IDs as well as data are int. Children are called left and right. The project is split into 3 files, user.c, bintree.c, and bintree.h. The header file is #include'd in both the C scripts. user.c is where all the interaction is done - see bintree.h for the available functions as well as the binary tree node struct's definition. I will leave the original instructor comments in for clarity (the boilerplate can be obtained from the link above). user.c #include <stdio.h> #include "bintree.h" #include <stdlib.h> int main() { /* Insert your test code here. Try inserting nodes then searching for them. When we grade, we will overwrite your main function with our own sequence of insertions and deletions to test your implementation. If you change the argument or return types of the binary tree functions, our grading code won't work! */ return 0; } bintree.h #ifndef BINTREE_H #define BINTREE_H // Node structure should have an int node_id, an int data, and pointers to left and right child nodes typedef struct node { int node_id; int data; struct node *left; struct node *right; } node; ///*** DO NOT CHANGE ANY FUNCTION DEFINITIONS ***/// // Declare the tree modification functions below... void insert_node(int node_id, int data); int find_node_data(int node_id); void remove_node(int node_id); void delete_tree(); #endif
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree int find_node_data(int node_id); void remove_node(int node_id); void delete_tree(); #endif bintree.c // bintree.c interfaces with the node struct defined in bintree.h // to create and manipulate a heap-based binary tree. All functions // meant for interfacing by the user are defined in the header file. // // There is only ONE root (ie one tree), so there is only // one node of the tree with no parents. // // bintree.c assumes binary tree was built USING THE INSERT_NODE ALGORITHM! // It is *theoretically* possible to construct binary trees obeying // the (left,right)~(<,>)node_id equivalence (ie left-child has smaller node id than node_id, // right-child has larger node id than node_id) that lose the 'useful' property // of these trees: the extremely fast find_node_data algorithm, // relying on all nodes to the right of the root having // a larger node_id, and all nodes to the left having a smaller node_id. // That is, a binary tree could theoretically locally preserve the // equivalence property without it globally holding. Therefore, bintree.c // cannot be handed a root pointer from another heap-based binary tree interface // and be expected to work, unless the tree also globally preserves the equivalence. #include <stddef.h> // NULL def #include <stdlib.h> // malloc #include <stdio.h> // printf/scanf #include "bintree.h" #define ERROR_VAL -999999 // junk data value for find_node_data ///*** DO NOT CHANGE ANY FUNCTION DEFINITIONS ***/// // Initialize tree node *root = NULL;
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree ///*** DO NOT CHANGE ANY FUNCTION DEFINITIONS ***/// // Initialize tree node *root = NULL; // Insert a new node into the binary tree with node_id and data void insert_node(int node_id, int data) { // reserve memory for node node *newNode = (node *)malloc(sizeof(node)); // initialize node values newNode->node_id = node_id; newNode->data = data; newNode->left = NULL; newNode->right = NULL; // if tree empty, use as root if (root == NULL) { root = newNode; return; } // if tree not empty, traverse tree // find parent and attach child node *tmp = root; while (1) { // go to right-child if higher id if (node_id > tmp->node_id) { // if no right-child, attach child if (tmp->right == NULL) { tmp->right = newNode; return; } else { tmp = tmp->right; } // go to left-child if lower id } else if (node_id < tmp->node_id) { // if no left-child, attach child if (tmp->left == NULL) { tmp->left = newNode; return; } else { tmp = tmp->left; } // if ids are equal, ask to replace data (keeps children) } else if (node_id == tmp->node_id) { char ans; while(1) { printf("node id occupied. replace data? (y)/(n): "); scanf("%c", &ans); if ( ans == 'y') { tmp->data = data; return; } else if ( ans != 'n') { printf("invalid answer.\n"); continue; } } } } }
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree // Returns pointer to node's parent given node id node *find_parent(int node_id) { if (root == NULL) { printf("root is NULL\n"); return NULL; } else if (root->node_id == node_id) { return NULL; } // root has no parent node *tmp = root; node *parent = NULL; while (1) { if (tmp == NULL) { printf("no node found with node_id %d\n", node_id); return NULL; } // if node_id higher, go right; if lower, go left; if match, return else if ( (node_id > tmp->node_id) && (tmp->right != NULL) ) { parent = tmp; tmp = tmp->right; } else if ( (node_id < tmp->node_id) && (tmp->left != NULL) ) { parent = tmp; tmp = tmp->left; } else if (node_id == tmp->node_id) { // check to ensure is actually parent before return if ( (parent->left == tmp) || (parent->right == tmp) ) { return parent; } } else { // catch no matches tmp = NULL; } } } // Returns pointer to node given node_id node *find_node(int node_id) { if (root == NULL) { return NULL; } // no nodes at all else if (root->node_id == node_id) { return root; } // root has no parent node *tmp = find_parent(node_id); if (tmp == NULL) { return NULL; } // parent has node w/ node_id as left- or right-child else if ( (tmp->left != NULL) && ((tmp->left)->node_id == node_id) ) { return tmp->left; } else if (tmp->right != NULL) { return tmp->right; } // catch no matches return NULL; } // Find the node with node_id, and return its data int find_node_data(int node_id) { node *tmp = find_node(node_id); if (tmp == NULL) { return ERROR_VAL; } return tmp->data; }
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree /* OPTIONAL: Challenge yourself w/ deletion if you want Find and remove a node in the binary tree with node_id. Children nodes are fixed appropriately. */ void remove_node(int node_id) { node *parent = find_parent(node_id); node *tmp = find_node(node_id); if (tmp == NULL) { printf("remove_node failed, node DNE\n"); return; }
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree // • 'left-child' and 'right-child' refer to the // children of the node being deleted. // • 'appropriate leg' refers to whichever (left or right) // side of the parent the node being deleted is attached to. // // find the right-most descendent of the left-child (hence the highest node id less than node_id). // // - if no left-child, attach right-child to appropriate leg of tmp's parent. // // - otherwise, attach right-child to right-most descendent of left-child's right leg. // attach left-child to appropriate leg of tmp's parent. // // free tmp and return if (tmp->left == NULL) { if (tmp->right != NULL) { // catch root case if (parent == NULL) { root = tmp->right; } // otherwise attach right-child to appropriate leg of parent else if (parent->left == tmp) { parent->left = tmp->right; } else { parent->right = tmp->right; } } } else { // catch root case if (parent == NULL) { root = tmp->left; } // otherwise attach left-child to appropriate leg of parent else if (parent->left == tmp) { parent->left = tmp->left; } else { parent->right = tmp->left; } // and attach right-child to right-most descendent of left-child's right leg node *next = tmp->left; while (next->right != NULL) { next=next->right; } next->right = tmp->right; } free(tmp); return; } // For internal use by delete_tree, // recursively frees nodes of tree void delete_node(node *tmp) { if (tmp->left != NULL) { delete_node(tmp->left); } if (tmp->right != NULL) { delete_node(tmp->right); } free(tmp); }
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree // There is only one tree and it starts where 'root' points, // delete_tree unallocates all memory for every node connected // to root, including root. void delete_tree() { delete_node(root); } I would have liked to change find_node_data to be cast to a pointer so that NULL could be used to represent no result, but I wanted to stick to the grading scheme. This is a rudimentary assignment, so any discussion/critique is appreciated! How are my comments? Is the code concise, clear, efficient, and consistent (are there shorter algorithms, are my control structures convoluted, are my logic checks sound, is it readable, correct usage of macros)? Within the bounds of the guidelines, are there any gaps in my implementation?
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree Answer: General Observations The use of the typedef for the node struct is a good practice. The fact that all of the loops and if statements contain the code as blocks by using the braces ({ and }) is a good practice. It would be much easier to do a code review if we had the working test code. The lack of the working test code in the main() function in user.c makes it more difficult to review the code. Some users on this site might close the question as Missing Review Context. It really isn't clear why there is a node_id element in the node struct. Generally binary trees are ordered by the value of their contents (the data filed or member). Insertion into the tree should be based on the value of the data rather than the node ID. The code would be more portable if stdlib.h was included in user.c and the code returned either EXIT_FAILURE or EXIT_SUCCESS from main(). Since delete_node() is using recursion, it would probably be better if insert_node() used recursion to find the correct location for the node rather than a while loop. Convention When Using Memory Allocation in C When using malloc(), calloc() or realloc() in C a common convention is to sizeof(*PTR) rather sizeof(PTR_TYPE), this make the code easier to maintain and less error prone, since less editing is required if the type of the pointer changes. node* newNode = malloc(sizeof(*newNode));
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree In C there is no reason to cast the return value of malloc(). Test for Possible Memory Allocation Errors In modern high-level languages such as C++, memory allocation errors throw an exception that the programmer can catch. This is not the case in the C programming language. While it is rare in modern computers because there is so much memory, memory allocation can fail, especially if the code is working in a limited memory application such as embedded control systems. In the C programming language when memory allocation fails, the functions malloc(), calloc() and realloc() return NULL. Referencing any memory address through a NULL pointer results in undefined behavior (UB). Possible unknown behavior in this case can be a memory page error (in Unix this would be call Segmentation Violation), corrupted data in the program and in very old computers it could even cause the computer to reboot (corruption of the stack pointer). To prevent this undefined behavior a best practice is to always follow the memory allocation statement with a test that the pointer that was returned is not NULL. node* newNode = malloc(sizeof(node)); if (!newNode) { fprintf(stderr, "Malloc failed in insert_node()\n"); exit(EXIT_FAILURE); } A better practice would be to have a function that tests the allocation and returns status (NULL pointer in this case). static node* creat_node(int data) { node* newNode = malloc(sizeof(*newNode)); if (!newNode) { fprintf(stderr, "Malloc failed in insert_node()\n"); return NULL; } else { newNode->data = data; newNode->left = NULL; newNode->right = NULL; } return newNode; }
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
beginner, c, homework, binary-tree Avoid Global Variables It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation. In this case root is a global variable. You can make it a local variable by using the static keyword. // Initialize tree static node* root = NULL; Any functions that should be local such as delete_node() should be declared static as well. I am assuming delete_node() is local since it isn't included in bintree.h. This is also true for the find_parent() function.
{ "domain": "codereview.stackexchange", "id": 45437, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, c, homework, binary-tree", "url": null }
c++, recursion, template, c++20, constrained-templates Title: A recursive_all_of Template Function Implementation in C++ Question: This is a follow-up question for A recursive_foreach_all Template Function Implementation in C++. I am trying to implement recursive_all_of template function in this post. The experimental implementation recursive_all_of Template Functions Implementation namespace impl { template<std::ranges::input_range T, class UnaryPredicate> constexpr auto recursive_all_of(T& value, UnaryPredicate p) { return std::all_of(std::ranges::begin(value), std::ranges::end(value), p); } template<std::ranges::input_range T, class UnaryPredicate> requires(std::ranges::input_range<std::ranges::range_value_t<T>>) constexpr auto recursive_all_of(T& inputRange, UnaryPredicate p) { for (auto& item: inputRange) { if(impl::recursive_all_of(item, p) == false) return false; } return true; } } /* recursive_all_of template function */ template<std::ranges::input_range T, class UnaryPredicate> constexpr auto recursive_all_of(T& inputRange, UnaryPredicate p) { return impl::recursive_all_of(inputRange, p); } // A `recursive_all_of` Function Implementation in C++ #include <algorithm> #include <array> #include <chrono> #include <concepts> #include <deque> #include <execution> #include <exception> #include <functional> #include <iostream> #include <ranges> #include <string> #include <utility> #include <vector> // is_reservable concept template<class T> concept is_reservable = requires(T input) { input.reserve(1); }; // is_sized concept, https://codereview.stackexchange.com/a/283581/231235 template<class T> concept is_sized = requires(T x) { std::size(x); }; template<typename T> concept is_summable = requires(T x) { x + x; }; // recursive_unwrap_type_t struct implementation template<std::size_t, typename, typename...> struct recursive_unwrap_type { };
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...> { using type = std::ranges::range_value_t<Container1<Ts1...>>; }; template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...> { using type = typename recursive_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container1<Ts1...>> >::type; }; template<std::size_t unwrap_level, typename T1, typename... Ts> using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type; // recursive_variadic_invoke_result_t implementation template<std::size_t, typename, typename, typename...> struct recursive_variadic_invoke_result { }; template<typename F, class...Ts1, template<class...>class Container1, typename... Ts> struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...> { using type = Container1<std::invoke_result_t<F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>>; };
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts> requires ( std::ranges::input_range<Container1<Ts1...>> && requires { typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...> { using type = Container1< typename recursive_variadic_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container1<Ts1...>>, std::ranges::range_value_t<Ts>... >::type>; }; template<std::size_t unwrap_level, typename F, typename T1, typename... Ts> using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; // recursive_array_invoke_result implementation template<std::size_t, typename, typename, typename...> struct recursive_array_invoke_result { }; template< typename F, template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_invoke_result<1, F, Container<T, N>> { using type = Container< std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>, N>; };
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>> { using type = Container< typename recursive_array_invoke_result< unwrap_level - 1, F, std::ranges::range_value_t<Container<T, N>> >::type, N>; }; template< std::size_t unwrap_level, typename F, template<class, std::size_t> class Container, typename T, std::size_t N> using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type; // recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035 template<std::size_t, typename> struct recursive_array_unwrap_type { }; template<template<class, std::size_t> class Container, typename T, std::size_t N> struct recursive_array_unwrap_type<1, Container<T, N>> { using type = std::ranges::range_value_t<Container<T, N>>; };
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::size_t unwrap_level, template<class, std::size_t> class Container, typename T, std::size_t N> requires ( std::ranges::input_range<Container<T, N>> && requires { typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges struct recursive_array_unwrap_type<unwrap_level, Container<T, N>> { using type = typename recursive_array_unwrap_type< unwrap_level - 1, std::ranges::range_value_t<Container<T, N>> >::type; }; template<std::size_t unwrap_level, class Container> using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type; // https://codereview.stackexchange.com/a/253039/231235 template<template<class...> class Container = std::vector, std::size_t dim, class T> constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times)); } } template<std::size_t dim, std::size_t times, class T> constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output; for (size_t i = 0; i < times; i++) { output[i] = n_dim_array_generator<dim - 1, times>(input); } return output; } } // recursive_depth function implementation with target type template<typename T_Base, typename T> constexpr std::size_t recursive_depth() { return std::size_t{0}; }
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<typename T_Base, std::ranges::input_range Range> requires (!std::same_as<Range, T_Base>) constexpr std::size_t recursive_depth() { return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1}; } /* recursive_foreach_all template function performs specific function on input container exhaustively https://codereview.stackexchange.com/a/286525/231235 */ namespace impl { template<class F, class Proj = std::identity> struct recursive_for_each_state { F f; Proj proj; }; template<class T, class State> requires(!std::ranges::input_range<T>) constexpr void recursive_foreach_all(T& value, State& state) { std::invoke(state.f, std::invoke(state.proj, value)); } template<std::ranges::input_range T, class State> constexpr void recursive_foreach_all(T& inputRange, State& state) { for (auto& item: inputRange) impl::recursive_foreach_all(item, state); } template<class T, class State> requires(!std::ranges::input_range<T>) constexpr void recursive_reverse_foreach_all(T& value, State& state) { std::invoke(state.f, std::invoke(state.proj, value)); } template<std::ranges::input_range T, class State> constexpr void recursive_reverse_foreach_all(T& inputRange, State& state) { for (auto& item: inputRange | std::views::reverse) impl::recursive_reverse_foreach_all(item, state); } template<std::ranges::input_range T, class UnaryPredicate> constexpr auto recursive_all_of(T& value, UnaryPredicate p) { return std::all_of(std::ranges::begin(value), std::ranges::end(value), p); }
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }
c++, recursion, template, c++20, constrained-templates template<std::ranges::input_range T, class UnaryPredicate> requires(std::ranges::input_range<std::ranges::range_value_t<T>>) constexpr auto recursive_all_of(T& inputRange, UnaryPredicate p) { for (auto& item: inputRange) { if(impl::recursive_all_of(item, p) == false) return false; } return true; } } template<class T, class Proj = std::identity, class F> constexpr auto recursive_foreach_all(T& inputRange, F f, Proj proj = {}) { impl::recursive_for_each_state state(std::move(f), std::move(proj)); impl::recursive_foreach_all(inputRange, state); return std::make_pair(inputRange.end(), std::move(state.f)); } template<class T, class Proj = std::identity, class F> constexpr auto recursive_reverse_foreach_all(T& inputRange, F f, Proj proj = {}) { impl::recursive_for_each_state state(std::move(f), std::move(proj)); impl::recursive_reverse_foreach_all(inputRange, state); return std::make_pair(inputRange.end(), std::move(state.f)); } template<class T, class I, class F> constexpr auto recursive_fold_left_all(const T& inputRange, I init, F f) { recursive_foreach_all(inputRange, [&](auto& value) { init = std::invoke(f, init, value); }); return init; } template<class T, class I, class F> constexpr auto recursive_fold_right_all(const T& inputRange, I init, F f) { recursive_reverse_foreach_all(inputRange, [&](auto& value) { init = std::invoke(f, value, init); }); return init; } /* recursive_all_of template function */ template<std::ranges::input_range T, class UnaryPredicate> constexpr auto recursive_all_of(T& inputRange, UnaryPredicate p) { return impl::recursive_all_of(inputRange, p); }
{ "domain": "codereview.stackexchange", "id": 45438, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, recursion, template, c++20, constrained-templates", "url": null }