All Questions

Tagged with
Filter by
Sorted by
Tagged with
1910 votes
23 answers
241k views

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

One of the most interesting projects I've worked on in the past couple of years was a project about image processing. The goal was to develop a system to be able to recognize Coca-Cola 'cans' (note ...
Charles Menguy's user avatar
661 votes
32 answers
653k views

How do you compare float and double while accounting for precision loss?

What would be the most efficient way to compare two double or two float values? Simply doing this is not correct: bool CompareDoubles1 (double A, double B) { return A == B; } But something like: ...
Alex's user avatar
  • 6,651
634 votes
19 answers
746k views

How to replace all occurrences of a character in string?

What is the effective way to replace all occurrences of a character with another character in std::string?
big-z's user avatar
  • 6,972
408 votes
21 answers
350k views

Determine if two rectangles overlap each other?

I am trying to write a C++ program that takes the following inputs from the user to construct rectangles (between 2 and 5): height, width, x-pos, y-pos. All of these rectangles will exist parallel to ...
Rob Burke's user avatar
  • 5,445
358 votes
11 answers
255k views

Fast ceiling of an integer division in C / C++

Given integer values x and y, C and C++ both return as the quotient q = x/y the floor of the floating point equivalent. I'm interested in a method of returning the ceiling instead. For example, ceil(...
andand's user avatar
  • 17.3k
347 votes
2 answers
36k views

How to implement classic sorting algorithms in modern C++?

The std::sort algorithm (and its cousins std::partial_sort and std::nth_element) from the C++ Standard Library is in most implementations a complicated and hybrid amalgamation of more elementary ...
TemplateRex's user avatar
  • 69.9k
244 votes
29 answers
151k views

Detecting endianness programmatically in a C++ program

Is there a programmatic way to detect whether or not you are on a big-endian or little-endian architecture? I need to be able to write code that will execute on an Intel or PPC system and use exactly ...
Jay T's user avatar
  • 2,449
227 votes
19 answers
398k views

Which is the fastest algorithm to find prime numbers?

Which is the fastest algorithm to find out prime numbers using C++? I have used sieve's algorithm but I still want it to be faster!
kasperasky's user avatar
  • 3,201
214 votes
32 answers
195k views

Rounding up to the nearest multiple of a number

OK - I'm almost embarrassed posting this here (and I will delete if anyone votes to close) as it seems like a basic question. Is this the correct way to round up to a multiple of a number in C++? I ...
Robben_Ford_Fan_boy's user avatar
203 votes
6 answers
273k views

Rotating a point about another point (2D)

I'm trying to make a card game where the cards fan out. Right now to display it Im using the Allegro API which has a function: al_draw_rotated_bitmap(OBJECT_TO_ROTATE,CENTER_X,CENTER_Y,X ,Y,...
jmasterx's user avatar
  • 53.4k
202 votes
12 answers
13k views

Throwing the fattest people off of an overloaded airplane.

Let's say you've got an airplane, and it is low on fuel. Unless the plane drops 3000 pounds of passenger weight, it will not be able to reach the next airport. To save the maximum number of lives, ...
IvyMike's user avatar
  • 2,219
180 votes
6 answers
466k views

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping? [duplicate]

I am trying to efficiently make a copy of a vector. I see two possible approaches: std::vector<int> copyVecFast1(const std::vector<int>& original) { std::vector<int> newVec; ...
user avatar
151 votes
37 answers
19k views

Need for predictable random generator

I'm a web-game developer and I got a problem with random numbers. Let's say that a player has 20% chance to get a critical hit with his sword. That means, 1 out of 5 hits should be critical. The ...
130 votes
13 answers
33k views

Finding duplicates in O(n) time and O(1) space

Input: Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Goal : To find these repeating numbers in O(n) and using only ...
Zaki's user avatar
  • 1,325
128 votes
2 answers
48k views

std::back_inserter for a std::set?

I guess this is a simple question. I need to do something like this: std::set<int> s1, s2; s1 = getAnExcitingSet(); std::transform(s1.begin(), s1.end(), std::back_inserter(s2), ...
rlbond's user avatar
  • 66.7k
122 votes
13 answers
267k views

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I am looking for color space converter from RGB to HSV, specifically for the range 0 to 255 for both color spaces.
jmasterx's user avatar
  • 53.4k
122 votes
9 answers
47k views

Where can I get a "useful" C++ binary search algorithm?

I need a binary search algorithm that is compatible with the C++ STL containers, something like std::binary_search in the standard library's <algorithm> header, but I need it to return the ...
Robert Gould's user avatar
  • 69.3k
116 votes
16 answers
92k views

How can I test whether a number is a power of 2?

I need a function like this: // return true if 'n' is a power of 2, e.g. // is_power_of_2(16) => true // is_power_of_2(3) => false bool is_power_of_2(int n); Can anyone suggest how I could ...
Ant's user avatar
  • 1,171
116 votes
3 answers
30k views

Magic number in boost::hash_combine

The boost::hash_combine template function takes a reference to a hash (called seed) and an object v. According to the docs, it combines seed with the hash of v by seed ^= hash_value(v) + 0x9e3779b9 + (...
Fred Foo's user avatar
  • 360k
112 votes
19 answers
29k views

What is the fastest way to compute sin and cos together?

I would like to compute both the sine and co-sine of a value together (for example to create a rotation matrix). Of course I could compute them separately one after another like a = cos(x); b = sin(x);...
Danvil's user avatar
  • 22.6k
105 votes
10 answers
206k views

Calculate mean and standard deviation from a vector of samples in C++ using Boost

Is there a way to calculate mean and standard deviation for a vector containing samples using Boost? Or do I have to create an accumulator and feed the vector into it?
user393144's user avatar
  • 1,605
103 votes
6 answers
181k views

Finding the position of the maximum element

Is there a standard function that returns the position (not value) of the maximum element of an array of values? For example: Suppose I have an array like this: sampleArray = [1, 5, 2, 9, 4, 6, 3] I ...
Faken's user avatar
  • 11.6k
102 votes
4 answers
40k views

Difference between std::set and std::priority_queue

Since both std::priority_queue and std::set (and std::multiset) are data containers that store elements and allow you to access them in an ordered fashion, and have same insertion complexity O(log n), ...
penelope's user avatar
  • 8,369
98 votes
26 answers
74k views

Searching in a sorted and rotated array

While preparing for an interview I stumbled upon this interesting question: You've been given an array that is sorted and then rotated. For example: Let arr = [1,2,3,4,5], which is ...
Jones's user avatar
  • 983
95 votes
12 answers
143k views

What is the fastest way to transpose a matrix in C++?

I have a matrix (relatively big) that I need to transpose. For example assume that my matrix is a b c d e f g h i j k l m n o p q r I want the result be as follows: a g m b h n c I o d j p e k q f ...
mans's user avatar
  • 17.6k
94 votes
11 answers
93k views

Inverting a 4x4 matrix

I am looking for a sample code implementation on how to invert a 4x4 matrix. I know there is Gaussian eleminiation, LU decomposition, etc., but instead of looking at them in detail I am really just ...
clamp's user avatar
  • 33.5k
90 votes
14 answers
81k views

LRU cache design

Least Recently Used (LRU) Cache is to discard the least recently used items first How do you design and implement such a cache class? The design requirements are as follows: 1) find the item as fast ...
user297850's user avatar
  • 7,873
89 votes
6 answers
75k views

Difference between priority queue and a heap

It seems that a priority queue is just a heap with normal queue operations like insert, delete, top, etc. Is this the correct way to interpret a priority queue? I know you can build priority queues in ...
Mars's user avatar
  • 4,827
86 votes
9 answers
7k views

How to make a for loop variable const with the exception of the increment statement?

Consider a standard for loop: for (int i = 0; i < 10; ++i) { // do something with i } I want to prevent the variable i from being modified in the body of the for loop. However, I cannot ...
jhourback's user avatar
  • 4,431
86 votes
5 answers
51k views

Easiest way of using min priority queue with key update in C++

Sometimes during programming contests etc., we need a simple working implementation of min priority queue with decrease-key to implement Dijkstra algorithm etc.. I often use set< pair<key_value, ...
Chong Luo's user avatar
  • 1,091
84 votes
16 answers
132k views

Generating combinations in C++

I have been searching for a source code for generating combinations using C++. I found some advanced codes for this but that is good for only specific number predefined data. Can anyone give me some ...
Keneth Adrian's user avatar
83 votes
15 answers
197k views

Splitting a string by a character

I know this is a quite easy problem but I just want to solve it for myself once and for all I would simply like to split a string into an array using a character as the split delimiter. (Much like ...
Ali's user avatar
  • 5,398
82 votes
14 answers
189k views

Permutation of array

For example I have this array: int a[] = new int[]{3,4,6,2,1}; I need list of all permutations such that if one is like this, {3,2,1,4,6}, others must not be the same. I know that if the length of ...
user avatar
81 votes
10 answers
9k views

Does the range-based 'for' loop deprecate many simple algorithms?

Algorithm solution: std::generate(numbers.begin(), numbers.end(), rand); Range-based for-loop solution: for (int& x : numbers) x = rand(); Why would I want to use the more verbose std::...
fredoverflow's user avatar
79 votes
18 answers
73k views

Circular lock-free buffer

I'm in the process of designing a system which connects to one or more stream of data feeds and do some analysis on the data than trigger events based on the result. In a typical multi-threaded ...
Shing Yip's user avatar
  • 1,606
77 votes
13 answers
70k views

Fastest way to get the integer part of sqrt(n)?

As we know if n is not a perfect square, then sqrt(n) would not be an integer. Since I need only the integer part, I feel that calling sqrt(n) wouldn't be that fast, as it takes time to calculate the ...
Sarfaraz Nawaz's user avatar
72 votes
23 answers
86k views

How do I get the intersection between two arrays as a new array?

I faced this problem many times during various situations. It is generic to all programming languages although I am comfortable with C or Java. Let us consider two arrays (or collections): char[] A =...
Ranjan Sarma's user avatar
  • 1,575
71 votes
14 answers
210k views

Creating all possible k combinations of n items in C++

There are n people numbered from 1 to n. I have to write a code which produces and print all different combinations of k people from these n. Please explain the algorithm used for that.
Prannoy Mittal's user avatar
71 votes
3 answers
51k views

std::transform() and toupper(), no matching function

I tried the code from this question C++ std::transform() and toupper() ..why does this fail? #include <iostream> #include <algorithm> int main() { std::string s="hello"; std::string ...
Stack Overeem's user avatar
70 votes
9 answers
97k views

How to get a random element from a C++ container?

What is a good way to get a [pseudo-]random element from an STL range? The best I can come up with is to do std::random_shuffle(c.begin(), c.end()) and then take my random element from c.begin(). ...
paperjam's user avatar
  • 8,421
70 votes
8 answers
16k views

Emulate "double" using 2 "float"s

I am writing a program for an embedded hardware that only supports 32-bit single-precision floating-point arithmetic. The algorithm I am implementing, however, requires a 64-bit double-precision ...
user avatar
70 votes
14 answers
105k views

Fast String Hashing Algorithm with low collision rates with 32 bit integer [closed]

I have lots of unrelated named things that I'd like to do quick searches against. An "aardvark" is always an "aardvark" everywhere, so hashing the string and reusing the integer would work well to ...
Jason Citron's user avatar
69 votes
9 answers
12k views

Performance issue: Java vs C++

I have always heard that C++ was way more efficient than Java (and that is why most games are developed in C++). I wrote a small algorithm to solve the "Eight queens puzzle" in both Java and C++, ...
realUser404's user avatar
  • 2,171
69 votes
7 answers
7k views

How is vector<vector<int>> "heavier" than vector<pair<int,int>>?

During a recent interview, I suggested using vector<pair<int,int>> over vector<vector<int>> since we only wanted to store two values for every entry in the vector. I said ...
J. Doe's user avatar
  • 857
66 votes
10 answers
106k views

Most efficient/elegant way to clip a number?

Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lower and upper? Of course, ...
Alex Z's user avatar
  • 2,560
66 votes
16 answers
136k views

Efficiently getting all divisors of a given number

According to this post, we can get all divisors of a number through the following codes. for (int i = 1; i <= num; ++i){ if (num % i == 0) cout << i << endl; } For example,...
zangw's user avatar
  • 46.2k
66 votes
3 answers
3k views

Is there a nice way to assign std::minmax(a, b) to std::tie(a, b)?

std::tie(a, b) = std::minmax(a, b); I think this is intuitive code. Clean and understandable. Too bad it doesn't work as intended, as std::minmax templates for const&. If therefore the values are ...
Stack Danny's user avatar
  • 7,974
66 votes
4 answers
31k views

what is the difference between set and unordered_set in C++?

I came across this good question, which is similar but not at all same since it talks about Java, which has different implementation of hash-tables, by virtue of having synchronized accessor /mutators:...
Ajeet Ganga's user avatar
  • 8,492
64 votes
11 answers
189k views

Use of for_each on map elements

I have a map where I'd like to perform a call on every data type object member function. I yet know how to do this on any sequence but, is it possible to do it on an associative container? The ...
Antonio Pérez's user avatar
64 votes
10 answers
50k views

What is the right approach when using STL container for median calculation?

Let's say I need to retrieve the median from a sequence of 1000000 random numeric values. If using anything but std::list, I have no (built-in) way to sort sequence for median calculation. If using ...
sharkin's user avatar
  • 12.3k

1
2 3 4 5
253