I am trying to do the following with the STL vector. Say we have two vectors, both of the same dimension M. I want to copy part of a vector B into the other vector A, up to the element k-1. And the remaining part replace with something else. Here is Matlab code that does that
//like this?
vector<double> a, b;
... //fill a and b
for( int i = 0; i < k; i++ )
a[i] = b[i]; //copy from b to a
for( int i = k; i < a.size(); i++ )
a[i] = 0; //assign the remainder of a to 0 (or whatever)
I keep reading about how it is not a good practice to iterate over STL containers like Mathhead200 wrote. Is there more elegant way to do this?
Sort of...but he's iterating over a vector, so it's ok as long as you don't ever need to change the container type. If you want to be the most general...do what helios said.
Yes, I want to be able to change the container from vector to something else (don't know to what at the moment). That is why I don't want to do this in such a simple manner as Mathhead200 described. copy and fill work fine and it is easy to do lines 1 and 3 but I am still puzzled by line 2.
Next thing would be the question what kind of container does what I'm planning to do. For now, in the vector, I store some objects. I'd like to be able to search for a particular object. The search needs to be fast (binary search is preferable). To do that I need some hashing function (I saw that STL has some hashing algorithms. Will they hash objects?) than I need to sort those tags and than I'll be able to do the binary search. What container should I use?
The search needs to be fast (binary search is preferable). To do that I need some hashing function (I saw that STL has some hashing algorithms. Will they hash objects?) than I need to sort those tags and than I'll be able to do the binary search. What container should I use?
std::set should be what you're looking for. It requires that the contained objects can be ordered (i.e. they need an operator<). There's also std::[tr1::]unordered_set, which uses hashing instead.
OK. I rewrote my code so that I do not need what I wrote in my first post. But I need help with another problem. Say I want to store objects BV of class BaseVector in vector container. First object I generate with BV.first() and all next objects with BV.next() which returns true/false depending on how many objects I have created. The code below doesn't work. All elements of the vector are the same.
1 2 3 4 5 6 7 8 9 10 11
BaseVector BV;
std::vector<BaseVector>::iterator state;
resize(1000);
BV.first();
state = begin();
*state = BV;
while (BV.next())
{
++state;
*state = BV;
}