If I get some values from the keyboard, how can I find the middle value between them in real time?
this is what I have done but without any result :(
float *p=new float; //p points to the first element
float *my;
std::cin >> my;
vector<float*>V;
V.push_back(my);
std::vector<float*>::iterator it;
p=my;
while(my){
it=V.begin()+1;
}
int M =(*it-p)/2;
delete[] p;
to clarify: The middle in terms of order they were given
If you're trying to find the middle value in a container, it's pretty easy:
#include <iostream>
#include <vector>
int main() {
std::vector<float> v{1,2,3,4,5};
// Output: (1,2,3,4,5)
// 3 ^
std::cout << v.at(v.size()/2) << std::endl;
// Now a user provides another value, maybe
v.push_back(6);
// Output: (1,2,3,4,5,6)
// 4 ^
std::cout << v.at(v.size()/2) << std::endl;
}
Your code has... a lot of problems with pointers.
@Lightness explained it perfectly. here's another demo (-1 prints the current middle value, -2 exits)
#include <iostream>
#include <vector>
int main() {
std::vector<float> values;
float value;
while(std::cin >> value) {
if(value == -1 && values.size() > 0)
std::cout << "mid = " << values.at(values.size() / 2) << std::endl;
else if (value == -2)
break;
else
values.push_back(value);
}
}
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.