Skip to content

Commit

Permalink
Merge pull request #37205 from mantidproject/use_stl_alg_cppcheck
Browse files Browse the repository at this point in the history
CppCheck: use some stl algorithms
  • Loading branch information
SilkeSchomann committed Apr 30, 2024
2 parents 0bd2ff9 + eeadc63 commit 83f425f
Show file tree
Hide file tree
Showing 31 changed files with 217 additions and 338 deletions.
32 changes: 15 additions & 17 deletions Framework/API/src/AlgorithmManager.cpp
Expand Up @@ -111,17 +111,16 @@ IAlgorithm_sptr AlgorithmManagerImpl::getAlgorithm(AlgorithmID id) const {
*/
void AlgorithmManagerImpl::removeById(AlgorithmID id) {
std::lock_guard<std::recursive_mutex> _lock(this->m_managedMutex);
auto itend = m_managed_algs.end();
for (auto it = m_managed_algs.begin(); it != itend; ++it) {
if ((**it).getAlgorithmID() == id) {
if (!(*it)->isRunning()) {
g_log.debug() << "Removing algorithm " << (*it)->name() << '\n';
m_managed_algs.erase(it);
} else {
g_log.debug() << "Unable to remove algorithm " << (*it)->name() << ". The algorithm is running.\n";
}
break;
}
const auto it = std::find_if(m_managed_algs.cbegin(), m_managed_algs.cend(),
[&id](const auto &alg) { return alg->getAlgorithmID() == id; });
if (it == m_managed_algs.cend()) {
return;
}
if (!(*it)->isRunning()) {
g_log.debug() << "Removing algorithm " << (*it)->name() << '\n';
m_managed_algs.erase(it);
} else {
g_log.debug() << "Unable to remove algorithm " << (*it)->name() << ". The algorithm is running.\n";
}
}

Expand Down Expand Up @@ -174,12 +173,11 @@ size_t AlgorithmManagerImpl::removeFinishedAlgorithms() {
std::copy_if(m_managed_algs.cbegin(), m_managed_algs.cend(), std::back_inserter(theCompletedInstances),
[](const auto &algorithm) { return (algorithm->isReadyForGarbageCollection()); });
for (auto completedAlg : theCompletedInstances) {
auto itend = m_managed_algs.end();
for (auto it = m_managed_algs.begin(); it != itend; ++it) {
if ((**it).getAlgorithmID() == completedAlg->getAlgorithmID()) {
m_managed_algs.erase(it);
break;
}
const auto it = std::find_if(m_managed_algs.begin(), m_managed_algs.end(), [&completedAlg](const auto &alg) {
return alg->getAlgorithmID() == completedAlg->getAlgorithmID();
});
if (it != m_managed_algs.end()) {
m_managed_algs.erase(it);
}
}
return theCompletedInstances.size();
Expand Down
11 changes: 3 additions & 8 deletions Framework/API/src/FileProperty.cpp
Expand Up @@ -287,16 +287,11 @@ bool FileProperty::extsMatchRunFiles() {
try {
Kernel::FacilityInfo facilityInfo = Kernel::ConfigService::Instance().getFacility();
const std::vector<std::string> facilityExts = facilityInfo.extensions();
auto facilityExtsBegin = facilityExts.cbegin();
auto facilityExtsEnd = facilityExts.cend();
const std::vector<std::string> allowedExts = this->allowedValues();
match = std::any_of(allowedExts.cbegin(), allowedExts.cend(), [&facilityExts](const auto &ext) {
return std::find(facilityExts.cbegin(), facilityExts.cend(), ext) != facilityExts.cend();
});

for (const auto &ext : allowedExts) {
if (std::find(facilityExtsBegin, facilityExtsEnd, ext) != facilityExtsEnd) {
match = true;
break;
}
}
} catch (Mantid::Kernel::Exception::NotFoundError &) {
} // facility could not be found, do nothing this will return the default
// match of false
Expand Down
16 changes: 8 additions & 8 deletions Framework/API/src/IFunction.cpp
Expand Up @@ -417,11 +417,10 @@ IConstraint *IFunction::getConstraint(size_t i) const {
*/
void IFunction::removeConstraint(const std::string &parName) {
size_t iPar = parameterIndex(parName);
for (auto it = m_constraints.begin(); it != m_constraints.end(); ++it) {
if (iPar == (**it).getLocalIndex()) {
m_constraints.erase(it);
break;
}
const auto it = std::find_if(m_constraints.cbegin(), m_constraints.cend(),
[&iPar](const auto &constraint) { return iPar == constraint->getLocalIndex(); });
if (it != m_constraints.cend()) {
m_constraints.erase(it);
}
}

Expand Down Expand Up @@ -456,7 +455,7 @@ void IFunction::setUpForFit() {
std::string IFunction::writeConstraints() const {
std::ostringstream stream;
bool first = true;
for (auto &constrint : m_constraints) {
for (const auto &constrint : m_constraints) {
if (constrint->isDefault())
continue;
if (!first) {
Expand Down Expand Up @@ -730,7 +729,7 @@ std::string IFunction::Attribute::asUnquotedString() const {
if (*(attr.begin()) == '\"')
unquoted = std::string(attr.begin() + 1, attr.end() - 1);
if (*(unquoted.end() - 1) == '\"')
unquoted = std::string(unquoted.begin(), unquoted.end() - 1);
unquoted.resize(unquoted.size() - 1);

return unquoted;
}
Expand Down Expand Up @@ -1674,7 +1673,8 @@ IPropertyManager::getValue<std::shared_ptr<Mantid::API::IFunction>>(const std::s
template <>
MANTID_API_DLL std::shared_ptr<const Mantid::API::IFunction>
IPropertyManager::getValue<std::shared_ptr<const Mantid::API::IFunction>>(const std::string &name) const {
auto *prop = dynamic_cast<PropertyWithValue<std::shared_ptr<Mantid::API::IFunction>> *>(getPointerToProperty(name));
const auto *prop =
dynamic_cast<PropertyWithValue<std::shared_ptr<Mantid::API::IFunction>> *>(getPointerToProperty(name));
if (prop) {
return prop->operator()();
} else {
Expand Down
2 changes: 1 addition & 1 deletion Framework/Algorithms/inc/MantidAlgorithms/FitPeaks.h
Expand Up @@ -214,7 +214,7 @@ class MANTID_ALGORITHMS_DLL FitPeaks final : public API::Algorithm {
const std::shared_ptr<FitPeaksAlgorithm::PeakFitResult> &fit_result);

/// calculate peak+background for fitted
void calculateFittedPeaks(std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> fit_results);
void calculateFittedPeaks(const std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> &fit_results);

/// Get the parameter name for peak height (I or height or etc)
std::string getPeakHeightParameterName(const API::IPeakFunction_const_sptr &peak_function);
Expand Down
15 changes: 8 additions & 7 deletions Framework/Algorithms/src/Bin2DPowderDiffraction.cpp
Expand Up @@ -321,17 +321,18 @@ void Bin2DPowderDiffraction::ReadBinsFromFile(std::vector<double> &Ybins,
* @param[in] Xbins --- bins to unify. Will be overwritten.
*/
size_t Bin2DPowderDiffraction::UnifyXBins(std::vector<std::vector<double>> &Xbins) const {
if (Xbins.size() == 0)
return 0;
// get maximal vector size
size_t max_size = 0;
for (const auto &v : Xbins) {
max_size = std::max(v.size(), max_size);
}
size_t maxSize = std::max_element(Xbins.cbegin(), Xbins.cend(), [](const auto &a, const auto &b) {
return a.size() < b.size();
})->size();
// resize all vectors to maximum size, fill last vector element at the end
for (auto &v : Xbins) {
if (v.size() < max_size)
v.resize(max_size, v.back());
if (v.size() < maxSize)
v.resize(maxSize, v.back());
}
return max_size;
return maxSize;
}

void Bin2DPowderDiffraction::normalizeToBinArea(const MatrixWorkspace_sptr &outWS) {
Expand Down
10 changes: 5 additions & 5 deletions Framework/Algorithms/src/ConjoinWorkspaces.cpp
Expand Up @@ -116,11 +116,11 @@ void ConjoinWorkspaces::checkForOverlap(const MatrixWorkspace &ws1, const Matrix
}
}
const auto &dets = spec.getDetectorIDs();
for (const auto &det : dets) {
if (detectors.find(det) != detectors.end()) {
g_log.error() << "The input workspaces have common detectors: " << (det) << "\n";
throw std::invalid_argument("The input workspaces have common detectors");
}
const auto it = std::find_if(dets.cbegin(), dets.cend(),
[&detectors](const auto &det) { return detectors.find(det) != detectors.cend(); });
if (it != dets.cend()) {
g_log.error() << "The input workspaces have common detectors: " << (*it) << std::endl;
throw std::invalid_argument("The input workspaces have common detectors");
}
}
}
Expand Down
10 changes: 4 additions & 6 deletions Framework/Algorithms/src/ConvertUnits.cpp
Expand Up @@ -317,9 +317,8 @@ MatrixWorkspace_sptr ConvertUnits::convertQuickly(const API::MatrixWorkspace_con
const bool commonBoundaries = inputWS->isCommonBins();
if (commonBoundaries) {
// Calculate the new (common) X values
for (auto &x : outputWS->mutableX(0)) {
x = factor * std::pow(x, power);
}
std::transform(outputWS->mutableX(0).cbegin(), outputWS->mutableX(0).cend(), outputWS->mutableX(0).begin(),
[&](const auto &x) { return factor * std::pow(x, power); });

auto xVals = outputWS->sharedX(0);

Expand All @@ -345,9 +344,8 @@ MatrixWorkspace_sptr ConvertUnits::convertQuickly(const API::MatrixWorkspace_con
for (int64_t k = 0; k < numberOfSpectra_i; ++k) {
PARALLEL_START_INTERRUPT_REGION
if (!commonBoundaries) {
for (auto &x : outputWS->mutableX(k)) {
x = factor * std::pow(x, power);
}
std::transform(outputWS->mutableX(k).cbegin(), outputWS->mutableX(k).cend(), outputWS->mutableX(k).begin(),
[&](const auto &x) { return factor * std::pow(x, power); });
}
// Convert the events themselves if necessary.
if (m_inputEvents) {
Expand Down
15 changes: 6 additions & 9 deletions Framework/Algorithms/src/FitPeaks.cpp
Expand Up @@ -496,14 +496,11 @@ std::map<std::string, std::string> FitPeaks::validateInputs() {
functionParameterNames.emplace_back(m_peakFunction->parameterName(i));
// check that the supplied names are in the function
// it is acceptable to be missing parameters
bool failed = false;
for (const auto &parName : suppliedParameterNames) {
if (std::find(functionParameterNames.begin(), functionParameterNames.end(), parName) ==
functionParameterNames.end()) {
failed = true;
break;
}
}
const bool failed = std::any_of(suppliedParameterNames.cbegin(), suppliedParameterNames.cend(),
[&functionParameterNames](const auto &parName) {
return std::find(functionParameterNames.begin(), functionParameterNames.end(),
parName) == functionParameterNames.end();
});
if (failed) {
std::string msg = "Specified invalid parameter for peak function";
if (haveCommonPeakParameters)
Expand Down Expand Up @@ -1473,7 +1470,7 @@ bool FitPeaks::processSinglePeakFitResult(size_t wsindex, size_t peakindex, cons
* fitted parameter
* table
*/
void FitPeaks::calculateFittedPeaks(std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> fit_results) {
void FitPeaks::calculateFittedPeaks(const std::vector<std::shared_ptr<FitPeaksAlgorithm::PeakFitResult>> &fit_results) {
// check
if (!m_fittedParamTable)
throw std::runtime_error("No parameters");
Expand Down
10 changes: 3 additions & 7 deletions Framework/CurveFitting/src/Algorithms/LeBailFunction.cpp
Expand Up @@ -477,13 +477,9 @@ bool LeBailFunction::calculateGroupPeakIntensities(vector<pair<double, IPowderDi
peak->function(localpeakvalue, datax);

// check data
size_t numbadpts(0);
vector<double>::const_iterator localpeakvalue_end = localpeakvalue.end();
for (auto it = localpeakvalue.begin(); it != localpeakvalue_end; ++it) {
if ((*it != 0.) && (*it < NEG_DBL_MAX || *it > DBL_MAX)) {
numbadpts++;
}
}
const auto numbadpts = std::count_if(localpeakvalue.cbegin(), localpeakvalue.cend(), [&](const auto &pt) {
return (pt != 0.) && (pt < NEG_DBL_MAX || pt > DBL_MAX);
});

// report the problem and/or integrate data
if (numbadpts == 0) {
Expand Down
30 changes: 14 additions & 16 deletions Framework/CurveFitting/src/ExcludeRangeFinder.cpp
Expand Up @@ -66,22 +66,20 @@ void ExcludeRangeFinder::findNextExcludedRange(double p) {
// m_exclude that is greater than p. If this point is a start than the
// end will be the following point. If it's an end then the start is
// the previous point. Keep index m_exclIndex pointing to the start.
for (auto it = m_exclude.begin() + m_exclIndex; it != m_exclude.end(); ++it) {
if (*it >= p) {
m_exclIndex = static_cast<std::size_t>(std::distance(m_exclude.begin(), it));
if (m_exclIndex % 2 == 0) {
// A number at an even position in m_exclude starts an exclude
// range
m_startExcludedRange = *it;
m_endExcludeRange = *(it + 1);
} else {
// A number at an odd position in m_exclude ends an exclude range
m_startExcludedRange = *(it - 1);
m_endExcludeRange = *it;
--m_exclIndex;
}
break;
}
const auto it = std::find_if(m_exclude.cbegin(), m_exclude.cend(), [&p](const auto &ex) { return ex >= p; });
if (it == m_exclude.cend())
return;
m_exclIndex = static_cast<std::size_t>(std::distance(m_exclude.begin(), it));
if (m_exclIndex % 2 == 0) {
// A number at an even position in m_exclude starts an exclude
// range
m_startExcludedRange = *it;
m_endExcludeRange = *(it + 1);
} else {
// A number at an odd position in m_exclude ends an exclude range
m_startExcludedRange = *(it - 1);
m_endExcludeRange = *it;
--m_exclIndex;
}
// No need for additional checks as p < m_exclude.back()
// and m_exclude[m_exclIndex] < p due to conditions at the calls
Expand Down
11 changes: 5 additions & 6 deletions Framework/CurveFitting/src/Functions/ProcessBackground.cpp
Expand Up @@ -366,11 +366,10 @@ void ProcessBackground::addRegion() {
}

// Check
for (auto it = vx.begin() + 1; it != vx.end(); ++it) {
if (*it <= *it - 1) {
g_log.error() << "The vector X with value inserted is not ordered incrementally\n";
throw std::runtime_error("Build new vector error!");
}
const auto it = std::adjacent_find(vx.cbegin(), vx.cend(), std::greater_equal<double>());
if (it != vx.cend()) {
g_log.error() << "The vector X with value inserted is not ordered incrementally" << std::endl;
throw std::runtime_error("Build new vector error!");
}

// Construct the new Workspace
Expand Down Expand Up @@ -504,7 +503,7 @@ void ProcessBackground::selectFromGivenFunction() {

auto bkgdorder = static_cast<int>(parmap.size() - 1); // A0 - A(n) total n+1 parameters
bkgdfunc->setAttributeValue("n", bkgdorder);
for (auto &mit : parmap) {
for (const auto &mit : parmap) {
string parname = mit.first;
double parvalue = mit.second;
bkgdfunc->setParameter(parname, parvalue);
Expand Down
Expand Up @@ -59,6 +59,7 @@ class MANTID_DATAHANDLING_DLL DetermineChunking : public API::Algorithm {
void exec() override;
std::string setTopEntryName(const std::string &filename);
FileType getFileType(const std::string &filename);
bool filenameHasExtension(const std::string &filename, const std::vector<std::string> &fileExtensions);
};

} // namespace DataHandling
Expand Down
4 changes: 2 additions & 2 deletions Framework/DataHandling/inc/MantidDataHandling/LoadHelper.h
Expand Up @@ -55,8 +55,8 @@ NeXus::NXDouble getDoubleDataset(const NeXus::NXEntry &, const std::string &);

void replaceZeroErrors(const API::MatrixWorkspace_sptr &, double);

void recurseAndAddNexusFieldsToWsRun(NXhandle nxfileID, API::Run &runDetails, std::string &parent_name,
std::string &parent_class, int level, bool useFullPath);
void recurseAndAddNexusFieldsToWsRun(NXhandle nxfileID, API::Run &runDetails, const std::string &parent_name,
const std::string &parent_class, int level, bool useFullPath);
} // namespace LoadHelper
} // namespace DataHandling
} // namespace Mantid
Expand Up @@ -68,7 +68,7 @@ class MANTID_DATAHANDLING_DLL LoadRawHelper : public API::IFileLoader<Kernel::Fi
static bool isIncludeMonitors(const std::string &monitorOption);

static void ProcessLoadMonitorOptions(bool &bincludeMonitors, bool &bseparateMonitors, bool &bexcludeMonitors,
API::Algorithm *const pAlgo);
const API::Algorithm *pAlgo);
/// creates monitor workspace
static void createMonitorWorkspace(DataObjects::Workspace2D_sptr &monws_sptr,
const DataObjects::Workspace2D_sptr &normalws_sptr,
Expand Down

0 comments on commit 83f425f

Please sign in to comment.