std::vector<int> vec; vector<int>* pVec = &vec; vec.reserve(10000); assert(pVec == &vec); is safe. std::vector<int> vec(1,0); int* p = &vec[0]; // some operation here assert(p == &vec[0]); is not safe. The first block is safe since the address vec will not change even when its contents change. The second block is not...
r,for-loop,matrix,vector,conditional
Using sapply and ifelse : sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) You loop over the positive values (you should also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values. # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,]...
Here's a pretty simple solution which uses emplace_back and the vector range constructor: std::vector<std::vector<int>> intvec; //intvec filled somehow std::vector<std::vector<double>> doublevec; doublevec.reserve(intvec.size()); for (auto&& v : intvec) doublevec.emplace_back(std::begin(v), std::end(v)); ...
You didn't put any elements in your fin vector. Also you mistook ^ for power function. You need to use std::pow: Try: #include <cmath> #include <vector> #include <iostream> using namespace std; int main () { vector<long long> a; vector<long long> fin(1); // add an element for (int i = 0;...
You are taking in a std::string by non-const reference. Non-const references cannot bind to rvalues, like "10h;", so you can't pass literals in to that function. If you aren't going to modify the argument, you should take your argument by reference-to-const: void Node::set_val(const string &val) // ^^^^^ This way, a...
One issue right away: Simple* simple_obj; int number = simple_obj->getSampleCounts(infile); simple_obj is an uninitialized pointer, thus your program exhibits undefined behavior at this point. Why use a pointer anyway? You could have simply done this to avoid the issue: Simple simple_obj; simple_obj.getSampleCounts(infile); Also, this line may not be an issue,...
What is happening is that tPeca pecaJogo[tam]; is a local variable, and as such the whole array is allocated in the stack frame of the function, which means that it will be deallocated along with the stack frame where the function it self is loaded. The reason it's working is...
javascript,vector,openlayers,openlayers-3
Just change this: var points = [ new ol.geom.Point([78.65, -32.65]), new ol.geom.Point([-98.65, 12.65]) ]; To: var points = [ [78.65, -32.65], [-98.65, 12.65] ]; The ol.geom.LineString constructor accept an array of coordinates....
try this: M + rep(x, each = nrow(M)) or this: apply(M, 1, `+`, x) result: [,1] [,2] [,3] [1,] 6 7 8 [2,] 7 8 9 [3,] 8 9 10 EDIT: akrun commented on two other great solutions: M + x[col(M)] and sweep(M, 2, x, "+") ...
Try match where 'm1' is the matrix match(vector1, m1[,1]) #[1] 2 1 2 3 Or unname(setNames(as.numeric(m1[,2]), m1[,1])[vector1]) #[1] 2 1 2 3 ...
Your C++ matrices are probably stored as row major under the hood. Which means that multiplying them from left to right is an "origin" transformation, while right to left would be a "local" incremental transformation. OpenGL however uses a column major ordering memory layout (The 13th, 14th and 15th elements...
That is because A::complex and B::complex are different types (with same content, but that does not matter). So that vector<A::complex> and vector<B::complex> are different. Move definition of struct complex outside A and B. Also there are more issues in your code. A::getPointerToVector does nothing, because it copies input vector iterator...
c++,vector,move-semantics,erase
The moves have no effect because Card has no move constructor or move assignment operator. The vectors deck1 and deck2 contain copies of whatever is pushed into them. But the problem (or at least, one problem) is that you invalidate p when you erase from deck1. De-referencing p is undefined...
symfony2,vector,datagrid,doctrine2
I ended up using an Entity source instead of a Vector, and because the data was from a stored procedure/native query, it was imposible for doctrine to find me the current row with the id, so my client ended up creating a new stored procedure that uses the row id...
Your problem comes from this line: unique_ptr<vector<int[]>> m_indices; You should use a stl container instead, in this case it could be a vector of vector Also, why would you need a unique_ptr in this case? vectors support move semantics and you could just have a vector<vector<int>> m_indices; An extra hint...
Your loops are not taking into account that when you erase() an element from a vector, the indexes of the remaining elements will decrement accordingly. So your loops will eventually exceed the bounds of the vector once you have erased at least 1 element. You need to take that into...
I think you can try this, Thanks for @JacobH comment, this will be faster. x <- c(0,0,1,0,1,1,0) zeros <- which(x > 0) x[zeros[1]:tail(zeros, n = 1)] the output [1] 1 0 1 1 ...
c++,string,if-statement,vector
The first line places string beginning with 'abc' at the end, and the second erases them from the vector. auto end_it = std::remove_if(myvec.begin(), myvec.end(), [](const string &str){ return str.find("abc") == 0 ;}) ; myvec.erase(end_it, myvec.end()) ; ...
Generate the points in the straight position then apply the rotation (also check the origin of the coordinates).
I would suggest you to use the .size() function instead of defining a new constant. Why? Safety : Since .size() does not throw any exceptions, it is perfectly safe to use .size(). Readability : IMHO, Bodies.size() conveys the size of the vector Bodies more clearly than NumParticles. Convention : According...
c++,multithreading,c++11,vector,stdthread
You need to use something like readerThreads.push_back(move(th)); This will make th an rvalue, and cause the move ctor to be called. The copy ctor of thread was disabled by design (see Anthony Williams' C++ Concurrency In Action)....
If you do not have virtual destructor in your Node class, deleting your Directory objects through base class pointer is undefined behaviour. Your Directory class' s destructor won't be called, also the destructor of the contained vector. This might cause the memory leak.
java,database,swing,vector,stringbuffer
You're adding an ActionListener to the submit button repeatedly within the addStudent ActionListener, meaning as addStudent is pressed, more and more ActionListeners will be added to submit and this is not what you want. Suggestions: Add an ActionListener just once to your JButtons and not within other event listeners which...
+= is a binary operator. The function friend std::vector<Employee*>& operator+=(const Employee* emp) { _table.push_back(emp->clone()); return *this; } defines a non-member function that can take only one argument. Hence, it cannot be used in an expression like: a += b; What you need is: Company& operator+=(const Employee* emp) { _table.push_back(emp->clone()); return...
We could use rleid to create another grouping variable, get the mean of 'y', and assign the 'indx' to NULL library(data.table) # v 1.9.5+ DT[, .(my = mean(y)), by = .(indx = rleid(x), x)][, indx := NULL] # x my #1: 19 54 #2: 21 38 #3: 19 47 #4:...
The example can be written as: let mut list = (0..10).collect::<Vec<u32>>(); list.retain(|element| element % 2 == 0); assert_eq!(&list[..], &[0, 2, 4, 6, 8]); The relevant documentation can be found here: https://doc.rust-lang.org/std/vec/struct.Vec.html...
It really depends what you want to do. Make a vector of length 5, filled with ones: std::vector<int> vec(5, 1); Grow a vector by 5 and fill it with ones: std::vector<int> vec; // ... vec.insert(vec.end(), 5, 1); Or resize it (if you know the initial size): std::vector<int> vec(0); vec.resize(5, 1);...
A std::vector<LPWSTR> is a std::vector<wchar_t*> (since LPWSTR is a typedef for wchar_t*). Now, having a vector of raw owning pointers is very fragile. You can have a vector of raw observing pointers, and you must be sure that the strings pointed to are still allocated (kind of "live") when you...
Scilab doesn't have a direct analogue of Python's fcn(*v) function call that would interpret the entries of v as multiple arguments. If you want to be able to call your function as either fcn(1,2,3,4,5,6) or as v = 1:6; fcn(v), then you'll need to add this clause to its beginning:...
You need to pass by reference; by making a copy, you sort a temporary copy, and then that's it; it disappears and the original is still unsorted, because, once again, you sorted only a temporary copy of the entire vector. So change vector<int> a to vector<int>& a. Here's the code,...
c++,opencv,vector,feature-extraction,heap-corruption
Try putting matches.reserve(size) with the actually size of the vector, before insert any element. This is necessary if you're using the OpenCV 2.2, but not with the 2.9...
Yes, those objects still exist and you must delete them. Alternatively you could use std::vector<std::unique_ptr<myObject>> instead, so that your objects are deleted automatically. Or you could just not use dynamic allocation as it is more expensive and error-prone. Also note that you are misusing reserve. You either want to use...
c++,vector,destructor,clear,dynamic-allocation
Yes, the vector's destructor will be called, and this will clear its contents. delete calls the destructor before de-allocating memory, and vector's destructor implicitly calls .clear() (as you know from letting an automatic-storage duration vector fall out of scope). This is quite easy to test, with a vector<T> where T...
You forgot the return statement in the function bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { i.second.first < j.second.first ; } Write instead bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { return i.second.first < j.second.first ; } Also you should include header <utility> where class std::pair...
Strings and vectors both store their content contiguously. If there's not enough room for adding a new element, the capacity must be increased (memory allocation) and the existing content must be moved to the new location. Hence, the performance should depend significantly on the allocation strategy of your implementation. If...
Your comparisons contain inconsistencies which would explain the differences, and another factor could be the result of compiling without sufficient optimization. Some implementations have a lot of additional code in the debug builds of STL, for instance MSVC does bounds checking on vector element accesses that produce a significant reduction...
The error location is 0x00000044, which usually means that this was NULL in the method call, while it is trying to access a member variable (at location this+0x44 in this case). Check that you are not calling addArtist() on a NULL Company* pointer....
The problem is that your operator= only works on individual elements, not on whole vectors. You need to define a constructor that converts an A into a B. Then you can use std::vector::assign rather than std::vector::operator=. #include <iostream> #include <vector> using namespace std; struct A { int x, y; A():...
c++,arrays,string,vector,segmentation-fault
You said: I have some C++ code where I'm taking input from a user, adding it to a vector splitting the string by delimiter, and for debugging purposes, printing the vector's contents. And your code does: while (true) { //Prints current working directory cout<<cCurrentPath<<": "; /// /// This line of...
c++,vector,boolean,const,extraction-operator
Despite the name, vector<bool> contains no bools, and dereferencing its iterator doesn't give you a bool&. Instead, it gives you an object of type vector<bool>::reference, which tries to imitate the behavior of bool& as much as it can. There's no way to convert a vector<bool>::reference to a bool&, so the...
r,string,vector,data.frame,numeric
Try match(v1, unique(v1)) #[1] 1 2 3 4 2 1 Or as.numeric(factor(v1, levels=unique(v1))) #[1] 1 2 3 4 2 1 data v1 <- c('Peter', 'Paul', 'John', 'Melissa', 'Paul', 'Peter') ...
In you first example the function is called "getVector" which is appropriate to describe what the function does. It returns a vector with a certain number of elements, as expected. In the second example the same does not apply. The function is still called "getVector" but now you want to...
I don't think so these warnings would hang your IDE, these are harmless. And also it is always a best practice to specify the type for generics like Vectar<Object> or Vectar<String> or List<String> or ArrayList<String> etc and not use raw types. Please read from updated sources and books. It is...
c++,opencv,for-loop,dictionary,vector
for 20000 random points with about 27 neighbors for each point this function gave me a speed-up. It needed about 33% less time than your original method. std::vector<std::vector<cv::Point> > findNeighborsOptimized(std::vector<cv::Point> p, float maxDistance = 3.0f) { std::vector<std::vector<cv::Point> > centerbox(p.size()); // already create a output vector for each input point /*...
You are adding the same object to cols over and over again since col is always the same object. Keep in mind, that you handle objects by references (eventhough Java is alway pass-by-value, if you pass an object to a method, you actually pass the object-reference, not the object itself)....
python,numpy,vector,euclidean-distance
You could use cdist from scipy.spatial.distance to efficiently get the euclidean distances and then use np.argmin to get the indices corresponding to minimum values and use those to index into B for the final output. Here's the implementation - import numpy as np from scipy.spatial.distance import cdist C = B[np.argmin(cdist(A,B),1)]...
c++,arrays,vector,segmentation-fault
You have a vector nested inside of a vector. Note the term nested. That implies that you need a nested loop of some kind to access the inner-most vector. Let's have a simple example: std::vector<std::vector<AObject*>> vect; //... std::vector<AObject*> inner = {new AObject, new AObject, new AObject}; //... vect.push_back(inner); vect.push_back(inner); vect.push_back(inner);...
c,vector,void-pointers,memory-alignment,avx
_mm256_store_pd does not return anything. Remove assignment to ymm3: _mm256_store_pd((double*)res, ymm3); Also you don't need to cast res as it is already double*...
arrays,matlab,vector,slider,value
I would suggest to create a 1 x 10 vector of zeros when starting the GUI, i.e. in the OpeningFcn of the GUI: handles.X = zeros(1,10); guidata(hObject,handles); % Update handles variable Then in the Callback function of the slider, you always shift the vector one to the right and add...
This is one way of doing it with numpy: np.where(np.equal(Predictions, Labels)) which is equivalent to: np.equal(Predictions, Labels).nonzero() It will return a single element tuple though, so to get the actual array, add [0] as in: np.equal(Predictions, Labels).nonzero()[0] ...
python,vector,linear-algebra,mathematical-optimization,approximate
I agree that in general this is a pretty tough optimization problem, especially at the scale you're describing. Each objective function evaluation requires O(nm + n^2) work for n points of dimension m -- O(nm) to compute distances from each point to the new point and O(n^2) to compute the...
tl;dr answer: what are the pro's and cons of each[?] [] doesn't do bounds-checking, i.e. it is unsafer and slightly faster. at does bounds-checking, i.e. it is safer and slightly slower. Good rule of thumb: If performance is not a problem, use at, otherwise, use []....
Assuming that you want to get the rowSums of columns that have 'Windows' as column names, we subset the dataset ("sep1") using grep. Then get the rowSums(Sub1), divide by the rowSums of all the numeric columns (sep1[4:7]), multiply by 100, and assign the results to a new column ("newCol") Sub1...
Thanks for all the help guys, I think I managed to solve the problem. I changed the code for the array assignment to this std::vector<unsigned short> array(sub_image.begin<unsigned short>(),sub_image.end<unsigned short>()); and now the size is correct roi_size*roi_size thanks again for the help....
arrays,matlab,vector,double,complex-numbers
You can temporarily "remove" the minus sign, which causes the complex numbers: vec = [-2.5, 2, -1.5 , 1, -0.5, 0]; sign_vec = sign(vec); test = sign_vec.*((sign_vec.*vec).^1.4623); This results in: test = -3.8186 2.7555 -1.8092 1.0000 -0.3629 0 A generic way of your conversion involves the abs function: >> test...
You cannot push back a matrix into a vector. What you can do is preallocate memory for your vector (for speeding things up) then use the std::vector<>::assign member function to "copy" from the matrix into the vector: vector<int> collectionSum(gray.rows * gray.cols); // reserve memory, faster collectionSum.assign(*auxMat, *auxMat + gray.rows *...
Just need to add after if (!found) { break; } that else { found = false; } If it is equal relationship.size() that means that no one item has been found. Anyway, found was not updated to false after each for loop, so if it find just one time an...
c++,vector,shared-ptr,smart-pointers,shuffle
No, there is nothing bad or inefficient in this. std::random_shuffle only swaps the elements of the cointainer in some random way. std::swap is specialized for std::shared_ptr's, so it is safe and as efficient as swapping two pairs of raw pointers, without lots of reference counts could be going up and...
With vector type detection you might do: #include <iostream> #include <vector> // is_vector // ========= namespace Detail { template<typename T> struct is_vector_test { static constexpr bool value = false; }; template<typename ... Types> struct is_vector_test<std::vector<Types...>> { static constexpr bool value = true; }; } template<typename T> struct is_vector : Detail::is_vector_test<typename...
The main idea is to create Bus of type you need. I did it this way: num = zeros(15,15,15); move = zeros(15,15,15); a = struct('number',num,'movement', move); busInfo = Simulink.Bus.createObject(a); You can see it's possible to create any data structure, array, vector anything you want and then create Bus Signal of...
If you transpose the data, it's as easy as sorting the vectors by the index of the first element in them. This will be slower than your solution but may be more readable: void fix_order(std::vector<std::vector<std::string>>& data, const std::vector<std::string>& correct) { // setup index map, e.g. "first" --> 0 std::unordered_map<std::string, size_t>...
c++,c++11,vector,multidimensional-array
If the legacy code requires a char **, then to create a variable list, you can create a vector as you initially are doing in your question. After that, create a std::vector<char *>, where the pointers are pointers within the vector for each item. Of course, you have to ensure...
go for this, String name = String.valueOf(temp.get(0)); String value = String.valueOf(temp.get(1)); in case of Object.toString(), if the instance is null, a NullPointerException will be thrown, so, arguably, it's less safe.Whereas, using String.valueOf() you may not check for null. as ajb suggested you can handle ArrayIndexOutOfBoundsException by wrapping your code in...
If you simply want to erase everything off the vector, use: http://www.cplusplus.com/reference/vector/vector/erase/ It is the erase function for vectors // erase the first 3 elements: newcustomer.erase (newcustomer.begin(),newcustomer.begin()+3); ...
It's a condition to handle the case where the element you're trying to insert already exists in the vector. To explain this, let's start with defining the variables being used in the function. __p is a pointer to the position where you want to insert the new element __xr is...
The only error that I see is this>current_generation_.end() instead that ->. In addition you should consider declaring your compare fuction as accepting two const FPGA* instead that just FPGA*. This will force you to declare fitness() as const int fitness() const but it makes sense to have it const. Mind...
Try combn(v1, 2, FUN=function(x) paste(rev(x), collapse="-")) #[1] "B-A" "C-A" "D-A" "E-A" "C-B" "D-B" "E-B" "D-C" "E-C" "E-D" If you want in the default order combn(v1, 2, FUN=paste, collapse="-") #[1] "A-B" "A-C" "A-D" "A-E" "B-C" "B-D" "B-E" "C-D" "C-E" "D-E" Update For a faster option, you can use combnPrim from grBase....
The cost of the logarithmic number of reallocations you have to do is arguably irrelevant. However, you may consider using a std::deque that guarantees O(1) insertion at the front and at the end. You would lose contiguity, but some cache friendliness is kept. A deque is usually a decent trade-off,...
Not directly, as the vector of vectors does not store an array to its children data adresses. So you have to build this array std::vector<char*> temp(vec.size); for(unsigned int i=0;i<vec.size();i++) { temp[i] = vec[i].data(); } doSomething(temp.data()); ...
Here's one option b[lower.tri(b, diag=FALSE)] <- a b <- t(b) b # [,1] [,2] [,3] [,4] # [1,] 0 1 2 3 # [2,] 0 0 4 5 # [3,] 0 0 0 6 # [4,] 0 0 0 0 Alternatively, reorder a as required and assign that into the...
zipmap combines a series of keys and values, so you could do: (zipmap (iterate inc 1) data-vector) (with data-vector being your vector of maps) The reverse would basically be sorting by key, then taking all values, which can be written exactly like that: (->> data-map (sort-by key) (map val)) ...
c++,design-patterns,vector,segmentation-fault,copy-constructor
This may not solve all of your issues, but one thing you should do is to have your TCPClient pointer as a std::shared_ptr instead of a raw pointer. Given your description, you are indeed sharing the pointer between instances due to your usage of std::vector<ConcreteResynthesis>. You also mentioned that you...
python,vector,ipython,linear-algebra,ipython-notebook
If you do vector_sum(a) the local variable result will be the integer "1" in your first step which is not iterable. So I guess you simply should call your function vector_sum like vector_sum([a,b,a]) to sum up multiple vectors. Latter gives [4,7,10] on my machine. If you want to sum up...
As indicated by comment above, the answer is to use the follwing: for (i in 1:length(x)){ } What your code does is the following: First iteration: i set to the first value in x (1), uses i to look up 1st value in x (1). Second iteration: i set to...
My other answer on here explains why your approach failed and one possible approach for a solution. I just thought of a much, much simpler one that I thought was worth sharing. The problem is that you can't use a trailing return type because the function name itself isn't in...
I figure someone else might find this useful later so: if(PlayerPrefs.GetFloat("nodeNum") > 0) { //Assemble axis value arrays //X var xString = PlayerPrefs.GetString("xVals"); var xValues = xString.Split(","[0]); //Y var yString = PlayerPrefs.GetString("yVals"); var yValues = yString.Split(","[0]); //Z var zString = PlayerPrefs.GetString("zVals"); var zValues = zString.Split(","[0]); var countNode = 0; var...
c++11,vector,standards,emplace
Two options: 1) You can simply fix your test. You just need in you test preallocate enough memory first with vec1.reserve(10); Well, this is implementation details for std::vector. As more and more items are added to std::vector it needs to get more space for them. And this space must be...
To answer the question from your code : No, it's actually a very bad practice , and it will lead to undefined behavior. If sizeof(A) is equal to sizeof(B) your code might end up working ,considering that all functions derived in B and used inside f3 are virtual and non...
c++,class,object,inheritance,vector
Option 1 cannot work because obs is a vector<observable*>^. You cannot push a object of type observable because you can only store pointers (observable*) in it. You could store such objects in a vector<observable> but you cannot store Energy objects in such vector. Option 2 cannot work because ecause obs...
This will go inside the iterator library and give me errors along with "Conditional expression of type const Car is illegal" Your lambda function is expected to return a boolean value, not an object. Change it to copy_if(all.begin(), all.end(),fin.begin(), [&](const Car& cc) { return (cc.getModel()==model); }); It's meant to...
I am going to assume that your desired screen space runs from top to bottom so that {0, 0} is top left and {screenWidth, screenHeight} is bottom right. I am also going to assume that normalized device coordinates are in the range of [{-1, -1, 0}, {1, 1, 1}]. The...
To speed up insertion std::vector<T> allocate more memory (usually up to 2 times) than it needs so it doesn't have to reallocate every time an element is added. This greatly speed up insertion but potentially double the memory consumption. std::vector<T>.capacity() will give you the total capacity of the vector (ie...
The simplest way I can think of is; std::vector<char> buffer; // some code that places data into buffer char *c = new char[buffer.size()]; std::copy(buffer.begin(), buffer.end(), c); // use c delete [] c; std::copy() is available in the standard header <algorithm>. This assumes the code that places data into buffer explicitly...
Got the following example in STXXL:Sorter Section which addresses the same problem. Code: #include <stxxl/sorter> #include <stxxl/stats> #include <stxxl/timer> #include <stxxl/random> #include <limits> struct TwoInteger { int i, j; TwoInteger() { } TwoInteger(int _i, int _j) : i(_i), j(_j) { } }; struct TwoIntegerComparator { bool operator () (const TwoInteger&...
r,if-statement,recursion,vector,integer
Your sapply call is applying fun across all values of x, when you really want it to be applying across all values of i. To get the sapply to do what I assume you want to do, you can do the following: sapply(X = 1:length(x), FUN = fun, x =...
Try colSums(outer(a, x, FUN='>')) Or library(data.table) CJ(a,x)[,sum(V1>V2) ,V2]$V1 ...
(b->y < a->y - offset) || (b->y > a->y + offset) These are two different cases, which should have different results. I suppose that b is "less" then a in first case, and "greater" in the other case, but your code returns false for both cases. See @Jonathan's answer on...
There are multiple options to copy one vector to another. You can use std::copy algorithm, but need to include algorithm header file: #include<algorithm> std::copy(cityMap.begin(),cityMap.end(),std::back_inserter(startPop)); Or you can construct startPop using copy constructor as follows: startPop(cityMap); ...
You over-complicated your loop. Try something more like this instead: #include <vector> #include <string> #include <algorithm> using namespace std; // RL: omitting actual "bad" words to protect the innocent... const vector <string> bwords { "word1", "word2", "word3" }; string bleepWordIfBad(const string &word) { if (std::find(bwords.begin(), bwords.end(), word) != bwords.end()) return...