Use string instead of char*

This commit is contained in:
Cory Balaton 2023-10-04 12:57:36 +02:00
parent 07197c1902
commit 6307256edc
No known key found for this signature in database
GPG Key ID: 3E5FCEBFD80F432B
2 changed files with 42 additions and 17 deletions

View File

@ -15,10 +15,11 @@
#ifndef __UTILS__ #ifndef __UTILS__
#define __UTILS__ #define __UTILS__
#include <string> #include <armadillo>
#include <vector>
#include <iomanip> #include <iomanip>
#include <sstream> #include <sstream>
#include <string>
#include <vector>
/** @def DEBUG(msg) /** @def DEBUG(msg)
* @brief Writes a debug message * @brief Writes a debug message
@ -84,10 +85,24 @@ std::string scientific_format(const std::vector<double>& v,
* @param msg The message to be displayed * @param msg The message to be displayed
* */ * */
void m_assert(bool expr, void m_assert(bool expr,
const char* expr_str, std::string expr_str,
const char* func, std::string func,
const char* file, std::string file,
int line, int line,
const char* msg); std::string msg);
/** @brief Test if two armadillo vectors are close to each other.
*
* This function takes in 2 vectors and checks if they are approximately
* equal to each other given a tolerance.
*
* @param a Vector a
* @param b Vector b
* @param tol The tolerance
*
* @return Boolean
* */
bool arma_vector_close_to(arma::vec &a, arma::vec &b, double tol=1e-8);
#endif #endif

View File

@ -10,10 +10,6 @@
* @bug No known bugs * @bug No known bugs
* */ * */
#include "utils.hpp" #include "utils.hpp"
#include <cstdlib>
#include <cstring>
#include <string>
#include <bits/stdc++.h>
std::string scientific_format(double d, int width, int prec) std::string scientific_format(double d, int width, int prec)
{ {
@ -31,9 +27,9 @@ std::string scientific_format(const std::vector<double>& v, int width, int prec)
return ss.str(); return ss.str();
} }
static void print_message(const char* msg) static void print_message(std::string msg)
{ {
if (strlen(msg) > 0) { if (msg.size() > 0) {
std::cout << "message: " << msg << "\n\n"; std::cout << "message: " << msg << "\n\n";
} }
else { else {
@ -42,13 +38,13 @@ static void print_message(const char* msg)
} }
void m_assert(bool expr, void m_assert(bool expr,
const char* expr_str, std::string expr_str,
const char* f, std::string f,
const char* file, std::string file,
int line, int line,
const char* msg) std::string msg)
{ {
std::string new_assert(strlen(f) + (expr ? 4 : 6), '-'); std::string new_assert(f.size() + (expr ? 4 : 6), '-');
std::cout << "\x1B[36m" << new_assert << "\033[0m\n"; std::cout << "\x1B[36m" << new_assert << "\033[0m\n";
std::cout << f << ": "; std::cout << f << ": ";
if (expr) { if (expr) {
@ -63,3 +59,17 @@ void m_assert(bool expr,
abort(); abort();
} }
} }
bool arma_vector_close_to(arma::vec &a, arma::vec &b, double tol)
{
if (a.n_elem != b.n_elem) {
return false;
}
for (int i=0; i < a.n_elem; i++) {
if (std::abs(a(i) - b(i)) >= tol) {
return false;
}
}
return true;
}