简体   繁体   中英

C++ Most efficient way iterate specific contents in vector

I have two vectors, vec and p, such that p is a vector of pointers to different locations in vec.

So something like:

p[0] = &vec[12]
p[1] = &vec[20]
p[3] = &vec[1]

etc. p's size will always be less than or equal to vec, and will contain no duplicate references to the same location in vec.

What I'd like to have is some data structure that I can iterate through to get the dereferenced values of p in the order of the index they are pointing to in a. So for the above example, the result would need to iterate through in the order vec[1], vec[12], vec[20].

I know can get the position in vec the p is pointing to be doing something like p[i] - &vec[0] , and could probably implement this using std::sort and a custom comparing function, but I feel like there is a more efficient way to do this than the O(nlogn) of the sort function. I could also be completely wrong about that.

Thanks for any help!

After discarding a few mental ideas, I thought of a simple one:

std::vector<char> is_pointed_to(vec.size(), 0);//initialize the "bools" to "false"
//set is_pointed_to values
for(T* pointer : p) {
    size_t orig_index = pointer - &vec[0];
    is_pointed_to[orig_index] = 1; //set this index to "true"
}
//now do the iteration
for(int i=0; i<vec.size(); ++i) {
    if(is_pointed_to[i]) {
        //DO TASK HERE
    }
}

This is clearly a two-pass algorithm, so O(n). Easy.

StilesCrisis reminds me that this is an implementation of the counting sort .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM