373 questions
1
vote
1
answer
80
views
Can output range of algorithms in <numeric> in C++ overlap with the input range?
There are six algorithms that will output a range(which is denoted by an output iterator) in <numeric>: adjacent_difference, partial_sum, inclusive_scan, exclusive_scan, transform_inclusive_scan ...
5
votes
4
answers
315
views
Is there a safe (defined behaviour) way to use the STL to reduce the boilerplate of efficiently filtering a vector based off its indices?
I very often find myself wanting to filter a vector based on its index rather than its values.
auto some_values = std::vector{1, 0, 4, 6, 2};
// Somewhere I figure out which items to remove.
// This ...
1
vote
0
answers
148
views
How can I call ExecutionPolicy algorithms in a constexpr context?
I want to call standard library algorithms with the ExecutionPolicy for vectorization. At the same time the call should also work in a constexpr context. Unfortunately the ExecutionPolicy overloads of ...
2
votes
1
answer
263
views
Flatten vector of classes which contain vectors of structs
I have a vector of a class Planters which contain vectors of Plants. My goal is to return a vector of plants containing the plants from planter 1, followed by plants from planter 2, etc.
example: ...
1
vote
1
answer
918
views
How to filter and transform cpp vector to another type of vector?
I have a class called InfoBlob and two enums called Action and Emotion. My function is supposed to take in a vector<InfoBlobs> blobs, and return a vector<Action> actions, corresponding to ...
1
vote
1
answer
307
views
STL algorithm and (end of) arrays
I am new to C++. I was trying using the accumulate algorithm from the numeric library. Consider the following code segment.
int a[3] = {1, 2, 3};
int b = accumulate(a, a + 3, 0);
It turns out that ...
0
votes
1
answer
70
views
How should I assume which iterator category an algorithm uses?
Let's say :
std::sort(beg1, beg2, pred);
This algorithm takes a range of iterators for the container and a predicate. It takes an LegacyRandomAccessIterator.
I do understand the the 5 iterator ...
0
votes
1
answer
216
views
STL algorithm to get a per-vector-component min/max
I have a std::vector<vec3> points where vec3 has float x, y, z.
I want to find the min/max bounds of all the points. I.e. the min and max of all vec3::x, vec3::y, vec3::z separately in the ...
-1
votes
2
answers
278
views
How to replace a for-loop with STL based algorithm or range based loop?
Given a std::vector of vertices containing some 3d integer data:
struct Vertex{
int x;
int y;
int z;
}
std::vector<Vertex> vertices = {{10, 10, 10}, {20,20,20}, {30,30,30}, {40,40,...
23
votes
5
answers
4k
views
How can I convert std::vector<T> to a vector of pairs std::vector<std::pair<T,T>> using an STL algorithm?
I have a vector of integers:
std::vector<int> values = {1,2,3,4,5,6,7,8,9,10};
Given that values.size() will always be even.
I simply want to convert the adjacent elements into a pair, like ...
1
vote
1
answer
91
views
how to create custom intersected container from 2 distinct container types
Using the following containers:
std::vector<std::pair<std::string, int>> keyVals = {
{"A", 1}, {"B", 2}, {"C", 3}
};
std::vector<std::string> keys ...
2
votes
1
answer
104
views
C++ loop breaked 'cause the std::find algorithm
I have the next C++ code snippet:
...
static constexpr const char* my_char_array [10] { // Some literals here... } // Member of a class
std::vector<std::string> splitted_input { // Contains C++ ...
-1
votes
1
answer
353
views
Lambda function, arguments and logic in c++ [duplicate]
I am new to using lambda functions in C++. I have been researching the web, and found several articles, explaining the syntax and purpose of lambda function, but I have not come found articles which ...
3
votes
3
answers
333
views
How to erase non-alpha chars and lowercase the alpha chars in a single pass of a string?
Given a string:
std::string str{"This i_s A stRIng"};
Is it possible to transform it to lowercase and remove all non-alpha characters in a single pass?
Expected result:
this is a string
I ...
2
votes
2
answers
692
views
Standard algorithm to operate on adjacent elements
std::adjacent_find looks for the first two consecutive elements that satisfies the given predicate. I am looking for other algorithms that also has a predicate that takes the (previous, current) pair. ...
5
votes
1
answer
218
views
Why doesn't STL's implementation of next_permutation use the binary search?
I came up with this question after reading the excellent answer of std::next_permutation Implementation Explanation. Please refer to that post for an explanation of the algorithm used by STL, but I'll ...
3
votes
0
answers
57
views
What are the incentive of some std::ranges::XXX_n? [duplicate]
Looking through the algorithm library, there are a few std::ranges::XXX_n function have basically the same definition as their std::XXX_n counterparts, namely copy_n, fill_n, and generate_n.
The only ...
0
votes
1
answer
121
views
Algorithm name?: Concatenate the ranges returned by a function applied to each element of a range
Maybe I'm missing something. Is there a function in <algorithm> that does this? If not, what would you call it? It seems like a particular flavor of transform-reduce that is so specific it needs ...
0
votes
1
answer
187
views
How does the C++ algorithm library check the range of the output and not create segfaults when it is smaller than the range of the input?
I was just curious how some of the C++ algorithms check the range of the result/output container when you only provide the range of the input?
For example, for the following code
#include <iostream&...
4
votes
1
answer
169
views
Do the unseq execution policy require the iterators' value_type to be Cpp17CopyAssignable?
The following snipped does not compile with GCC 10 (Compiler Explorer link):
#include <vector>
#include <algorithm>
#include <execution>
struct T
{
int const ID; // Not ...
5
votes
1
answer
680
views
Is there something like std::remove() which does not preserve the order of retained elements of a vector?
In C++14, I have a std::vector of values for which I want to remove all elements that match a given value and I do not care about preserving the order of the elements after doing the remove. The ...
2
votes
2
answers
102
views
Avoid manual creation of lambda to wrap the call to new[]: to be used as a generator function in std::generate
Short Version
Currently, I manually create a lambda function for the new [], as follows:
[](){ return new double[3]; }
This lambda is later used as a generator function in the call to std::generate:
...
4
votes
4
answers
4k
views
C++ std:: string starts_with/ends_with case insensitive versions?
C++20 added starts_with, ends_with to std::string.
Is there a nice way to get it to be case insensitive?
Note that perf matters so I do not want to lowercase/uppercase both strings(or std::min(len1, ...
0
votes
1
answer
182
views
Swap() in STL algorithm C++
Why swap() in STL algorithm don't take address of a variable and passing variable work just fine but in C++ call by value don't change actual value but call by address changes actual parameter?
2
votes
1
answer
215
views
Call a member function of a vector of elements with a vector of arguments in parallel
Given this piece of code:
struct T
{
void f(int const);
};
void f(std::vector<T> &u, std::vector<int> const &v)
{
for (std::size_t i = 0; i < u.size(); ++i)
u[i].f(v[i]...
0
votes
1
answer
633
views
Sorting numbers digit wise
I have N numbers and I want to sort each number by digit. ( In my original problem I want to make the largest number by these (greedy approach)) For ex - If we have 5 numbers 9 1000 845 8000 56 In ...
2
votes
1
answer
654
views
Is a nested std::transform inefficient?
If I have a std::string:
std::string s{"hello"};
and a loop that modifies it in-place, like this:
for (auto &c: s)
c = std::toupper(c);
I can replace it with the equivalent transform:
std::...
1
vote
2
answers
1k
views
Using back_inserter to create vector from single member of struct
I'd like to know if it is possible to use std::back_inserter to create a vector of only a single element from a more complex struct. For example, in the following code:
struct Person {
std::string ...
0
votes
1
answer
169
views
Is it possible to rewrite my code using STL algorithms?
I have a nested loop and I am hoping to rewrite it using STL algorithms. Can someone help me out?
std::bitset<array_size * 8> bitset {};
short bitsetIndex {0};
for (int i = 0; i < array_size;...
2
votes
0
answers
75
views
Incorrect overload resolution in for_each_n? [duplicate]
The following program does not compile:
#include <algorithm>
#include <array>
#include <sstream>
int main()
{
std::stringstream s;
s << "1 2 3";
std::array<int,...
6
votes
1
answer
194
views
C++ Unexpected behavior with remove_if
I am trying to use std::remove_if to remove spaces from a simple string, but I am getting weird results. Could someone help me figure out what's going on?
The Code is:
#include <iostream>
#...
3
votes
0
answers
95
views
Why do stl algorithms take callables by value? [duplicate]
I stumbled upon this while trying something equivalent to
#include <vector>
#include <algorithm>
struct pred { //not copyable
pred () {}
bool operator()(int) const { return false;...
26
votes
3
answers
1k
views
Uniform initialization by tuple
Today, I arrived at a situation, where I have a vector of tuples, where the tuples might contain several entries. Now I wanted to convert my vector of tuples to a vector of objects, such that the ...
3
votes
1
answer
489
views
Parallel algorithm to sum-assign the elements of a vector to the elements of another one
Consider:
std::vector<double> u, v;
#pragma omp parallel for
for (std::size_t i = 0u; i < u.size(); ++i)
u[i] += v[i];
To express similar code with the C++17 parallel algorithms, the ...
0
votes
1
answer
409
views
Copy contents of a vector into a multiset
I've tried copying the contents of a std::vector into a std::multiset like this:
std::vector<unsigned> v(32768);
std::generate(v.begin(), v.end(), rand);
std::multiset<unsigned> m(v....
0
votes
1
answer
720
views
C++, copy_if with vector<class>
This is a part of the code, that I'm in trouble with
#include<iostream>
#include<fstream>
#include<conio.h>
#include<list>
#include<iterator>
#include<map>
#...
10
votes
1
answer
1k
views
Usage of for_each in the presence of exceptions? std::exception_list
cppreference documentation https://en.cppreference.com/w/cpp/algorithm/for_each
says that:
If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is ...
0
votes
2
answers
277
views
Code calling reverse function does not compile on either g++ or clang++ on Ubuntu 18, but mysteriously works on mac osx
On Mac OSX, clang version 7.0.2 the code compiles.
On Ubuntu clang version 7.0.0 it does not. Is there really a difference in some default library, this seems weird?
MWE:
#include <string>
...
0
votes
2
answers
461
views
Find minmax of custom data type using algorithm header
I have a vector of QPointF and I need to find the minimum and maximum y values because I need to know what is the amplitude of the data in the vector.
I use QPointF but for adding each new element I ...
0
votes
1
answer
658
views
Get an error using std::upper_bound on an Eigen library vector
I am trying to use std::upper_bound with a vector defined by the Eigen libraries. I get some errors on visual studio 2017
#include <stdafx.h>
#include <stdio.h>
#include <Eigen/Dense&...
8
votes
1
answer
442
views
Parallelizing a simple loop with c++17 algorithms
I have a parallel code that can be reduced to basically:
#include <algorithm>
#include <vector>
struct TKeyObjPtr;
class TObj
{
public:
virtual void Calculate(TKeyObjPtr const &) =...
4
votes
2
answers
221
views
Random unordered_multimap using std::generate
I'm trying to generate a random unordered_multimap of size 10 using the following code:
#include <algorithm>
#include <unordered_map>
#include <cstdlib>
int main()
{
auto m = ...
2
votes
1
answer
141
views
Shouldn't iterator_traits<vector<bool>::iterator>::iterator_category be input_iterator_tag?
I recently learned that ForwardIterators require operator * to return by reference, which means that iterators that
return proxies, such as std::vector<bool>, cannot be ForwardIterators
([...
-1
votes
2
answers
99
views
Counting and retrieving repetition using algorithm and lambda
I have a vector of structs like this:
struct Item {
int id;
string name;
}
vector<Item> v= ....;
Now I need to see how many unique "id" are in the vector and create another vector ...
-1
votes
2
answers
266
views
template argument deduction/substitution failed: is there no first, second for map?
I wish to sort the a std::map using the stl std::sort() but getting error on geeksforgeekside(cannot paste the whole error please see the link)
#include <bits/stdc++.h>
using namespace std;
...
0
votes
1
answer
497
views
Sorting a list of students by their grades in STL - C++? [duplicate]
I have a class Student with 2 member variables, one of which is grade. I create some students by the corresponding constructors and then put them in a list<Student>. I then want to use the sort()...
8
votes
3
answers
3k
views
C++ STL: Passing an empty container to lower_bound
Is the behavior for passing an empty container to std::lower_bound defined?
I checked cppreference.com and an old version of the C++ standard that I found online, but couldn't find a definite answer.
...
9
votes
4
answers
2k
views
Can STL algorithms and back_inserter preallocate space?
If I have something like:
vector<int> longVector = { ... };
vector<int> newVector;
transform(longVector.begin(), longVector.end(), back_inserter(newVector),
[] (int i) { return ...
0
votes
1
answer
266
views
partitioning a range of sorted elements into adjacent groups
I have a sorted list of items below. I need to determine how to pick [inclusive, exclusive) item pairs from this list such that the difference between them exceeds some fixed value (for example 5 in ...
2
votes
1
answer
606
views
How to take certain elements from one container and insert a transform of those into another container?
I have a vector<int*> and I want to place all pointed at elements into a vector<int>. All non-pointed at elements are set to nullptr.
I was thinking about doing something like this:
...