Populate a vector with linearly increased values
The first thing you could go is switch to using std::generate
or std::generate_n
instead of a for loop. The generate
version could look like
int main()
{
float a = 1.132;
std::vector<float> v(100);
std::generate(v.begin(), v.end(), [n = 0, &a]() mutable { return n++ * a; });
}
Another option is to create an iterator that will generate the value as you iterate it. This has the advantage that you do not need to initialize v
with any default constructed valued (this can be/is expensive). Then you use the vectors range constructor and it will initialize all of the elements. As long as the iterator abides by the forward iterator requirements then the vector will figure out the space needed (which if it is not random access causes a full iteration), allocate, and then initialize(full iteration). This could be expensive with the double iteration so it might not be any faster and could be slower then the generate case (since zero initializing is pretty fast).
Fill vector with unrepeated random numbers. why not working?
std::binary_search
only works on sorted ranges. Use std::find
instead:
while (std::find(ret.begin(), ret.end(), val) != ret.end())
Alternatively, you may use std::unordered_set
:
std::unordered_set<int> ret;
while (ret.size() < v_size) {
ret.insert(rand() % v_max);
}
Keep in mind that with this approach the order of the generated number will be unspecified, i.e. probably less random than the vector approach. If you want a sorted sequence of random numbers, consider std::set
.
Remark: The use of rand()
is discouraged in modern C++, although it will probably do the trick for toy programs. See also https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful
Populate vector with integer sequence, on construction
Don't over do it. The simple thing to do is to default initialize the vector, reserve and initialize from the range.
Make sure objects are initialized before they are used.
That does not mean that the member must be fully initialized in the initialization list, rather than the my_class
object must be fully initialized when the constructor completes.
Other than that, just for the sake of it, there are different things you can do in vanilla C++ to handle this, like creating a helper function and returning the vector by value:
std::vector<int> create_vector() {
std::vector<int> v;
// ...
return v;
}
But I would not use this (or any other alternative) to initialize a member, only if needed (the vector is const
might be sufficient excuse :))
Using std::iota to fill an alphabet vector
The behavior of std::iota is very simple:
Fills the range
[first, last)
with sequentially increasing values, starting withvalue
and repetitively evaluating++value
.
This means your code will only work when the encoding represents the characters 'a'
, 'b'
... 'z'
in increasing order. This is the case with ASCII encoding, so your code will work in that case. For any other encoding, where these characters are not increasing, or there are other characters interspersed between 'a'
and 'z'
, this will not work.
Comparing pushing data (1 million numbers) with and without prior resizing in std::vector
After this change: vec2.resize(times); it works faster
I think maybe that's because after the resize
the vec2
actually holds 2*times
space,so it does not need reallocating in later push_back
.
After this change: vec2.reserve(times); it works even faster
this version does not need reallocating,so it's better than the first one.
After this change: vec2[i] = i; becomes super fast
this directly place the element on its position,without any redundant operations compared with push_back
origin answer
You should do like:
vector<double> vec2;
vec2.resize(sizeof(double)* times); // this directly chage the size(),with capacity() also changed.
tp_start = chrono::high_resolution_clock::now();
for (double i = 0; i < times; i++)
{
vec2[i]=i;//not push_back
}
If you still use push_back
in this situation,it does not have any efficiency.
And in your example with resize
,the size of vec2
is larger than vec1
,which needs more time to reallocate its memory,and takes more time to do push_back
.By the way it's better to do reserve(n)
in your case.
Related Topics
C++11 Member Initializer List VS In-Class Initializer
Returning Const Reference to Local Variable from a Function
Is There Any Alternative to Using % (Modulus) in C/C++
When Can You Omit the File Extension in an #Include Directive
How to Check If the Program Is Run from a Console
How to Open a Gstreamer Pipeline from Opencv with Videowriter
Inserting into an Unordered_Set with Custom Hash Function
Detecting Usb Insertion/Removal Events in Windows Using C++
Get Current Time in Milliseconds Using C++ and Boost
Overloading Assignment Operator in C++
What Is Std::Decay and When It Should Be Used
What Exactly Is the Difference Between "Pass by Reference" in C and in C++
App Does Not Run with VS 2008 Sp1 Dlls, Previous Version Works with Rtm Versions
How to Find the Intersection of Two Stl Sets
Checking for Eof in String::Getline
C++: Deep Copying a Base Class Pointer