我正在尝试排序第一个向量 向量l [0]是x1的点,然后它的长度总是改变
vector<int> v1;
v1.push_back(l[0]);
vector<int>::iterator Iter = v1.begin();
for (Iter = v1.begin(); Iter != v1.end(); Iter++){
sort(v1.begin(), v1.end());
cout << *Iter << endl;
它没有任何错误,但无法按顺序排序。我怎么解决呢?
编辑---------------------------------------------- ------------------------------
void thresh_callback(int, void*)
{
/// Load source image and convert it to gray
src = imread(img_file, 1);
Mat threshold_output;
Mat threshold_output1;
Mat dst;
vector<vector<Point> > contours;
/// Detect edges using Threshold
Canny(src_hist, threshold_output, thresh, thresh * 3, 3, false);
Sharpen(threshold_output, threshold_output1);
cvtColor(threshold_output1, dst, CV_GRAY2BGR);
vector<Vec4i> lines;
HoughLinesP(threshold_output1, lines, 1, CV_PI / 180, thresh1, min_line, max_gap);
int erosion_size = 1;
Mat element = getStructuringElement(MORPH_ERODE,
Size(2 * erosion_size + 1, 2 * erosion_size + 1),
Point(erosion_size, erosion_size));
/// Apply the erosion operation
dilate(dst, dst, element);
imshow("Source", dst);
for (size_t i = 0; i < lines.size(); i++)
{
Vec4i l = lines[i];
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
int dx = l[2] - l[0];
int dy = l[3] - l[1];
double rad = atan2(dx, dy);
double degree = (rad * 180) / M_PI;
if (degree >= 180) degree -= 180;
if (degree < 15 || degree > 165) {
line(src, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1, 8);
//printf("%lf\n", degree);
//printf("%d, %d, %d, %d, %d\n", l[0], l[1], l[2], l[3], i);
vector<int> v1;
v1.push_back(l[0]);
vector<int>::iterator Iter = v1.begin();
sort(v1.begin(), v1.end());
for (Iter = v1.begin(); Iter != v1.end(); Iter++){
cout << *Iter << endl;
}
}
imshow("source", src);
}
}
我使用houghline并找出x1,x2,y1,y2的点 并得到每个x1和升序
答案 0 :(得分:4)
不确定这是您的问题,但是......您在v1
循环中定义for
。
for (size_t i = 0; i < lines.size(); i++)
{
// ...
vector<int> v1;
v1.push_back(l[0]);
vector<int>::iterator Iter = v1.begin();
sort(v1.begin(), v1.end());
for (Iter = v1.begin(); Iter != v1.end(); Iter++){
cout << *Iter << endl;
}
// ...
}
所以你,每次迭代,创建一个向量,插入一个元素,对向量进行排序(使用单个元素),打印单个值并销毁向量。
建议:在v1
循环之外定义for
。
---编辑---
正如aichao指出的那样,排序和打印部分可能在for循环之外更好;
之类的东西vector<int> v1;
for (size_t i = 0; i < lines.size(); i++)
{
// ...
v1.push_back(l[0]);
// ...
}
sort(v1.begin(), v1.end());
for ( vector<int>::const_iterator CIter = v1.cbegin(); CIter != v1.cend(); CIter++) {
cout << *CIter << endl;
}
如果你可以编译C ++ 11或C ++ 14,那么最后一个for
可以只是
for ( auto const & i : v1 )
cout << i << endl;
p.s:抱歉我的英语不好。