I would like to implement a function similar to the math function from excel, that is, given a vector and a value in the vector, return the relative position of that value in that container.

However, my code

vector<double> vec;
double x = 25.0;
int pos = 0;

for (int i = 0; i!=vec.size(); ++i) {
     if (x == vec[i])
     pos = i;

return pos;

is not as efficient as i wanted to be. What are more efficient ways to implement this simple function?

Thank you.

You could consider the find() or find_first_of() algorhithms or you could consider a map or multimap structure instead of a vector.

thank you. i'm new to map and could you fill me some details for me

map<double, int> counter;
vector<double> vec;
double x = 25.0;        // value to search for
int pos = 0;
int i = 0;
while (i < vec.size()) {
      i += 1;
pos = ++counter[!x];

am i on the right track with this? thanks

Member Avatar for iamthwee

When you say not efficient, how bad are we talking. How many values are in your little vector?

How long does it take to find the one you want?

Depending on your needs, map/multimap may not be what you want. If you want a brief overview here's a reference, though I'd recommend a good STL reference book if you don't already have one and want to start working with STL materials.


I suspect find() or find_first_of() is likely to be your best bet if the vector is unsorted. If the vector is sorted, then you may be able to use a more efficient search mechanism.

thank you all. i guess i'll stick to find() then.
my vectors usually have 10k+ elements and i have many of such vectors. my goal is just to maximize efficiency as much as possible...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.