我有一个文本文件 points.txt
由 Points/NotPoints , X ,Y 格式化
Points, [3, 3]
NotPoints, [0, 0]
Points, [4, 4]
NotPoints, [0, 0]
我想要做的是从文本文件中检索 X 值并将其放入向量中,然后按 ASC 或 DSC 顺序对 X 值进行排序。
我为我的问题找到了类似的帖子
www.stackoverflow.com/questions/7102246/sorting-a-vector-of-objects-in-c# =
但问题是,当我尝试在 main.cpp 中执行此操作时,
sort(pointsVector.begin(), pointsVector.end(),sortOrder()) ;
它显示一个错误,在 Points 类型的多个基类子对象中找到非静态成员 sortOrder。
请参阅下面的代码以了解我的实现。
我的任务的一些要求,
I must initialize int x as protected variable as there are other class inheriting it ,
I can't use struct therefore I am using get and set
代码
点数.h
#ifndef __Points__Points__
#define __Points__Points__
#include <iostream>
class Points {
friend class main;
protected:
int x;
int y;
private:
friend bool sortOrder (const Points & rhs, const Points & lhs);
public:
Points() {
x=0;
y=0;
};//default Constructor
Points (int x , int y);
int getX();
int getY();
void setX(int x);
void setY(int y);
bool sortOrder (const Point2D & rhs, const Point2D & lhs) {
return lhs.x < rhs.x;
}
};
#endif
点数.cpp
#include "Points.h"
Points::Points(int x , int y) {
setX(x);
setY(y);
}
int Points::getX() {
return x;
}
int Points::getY() {
return y;
}
void Points::setX(int x) {
this->x = x;
}
void Points::setY(int y) {
this->y = y;
}
主文件
#ifndef Points_main_h
#define Points_main_h
#include <iostream>
#include "Points.h"
#include <vector>
class main : public Points {
private:
int input;
std::string type,line;
std::string pointX, pointY;
std::vector<Points> pointsVector;
public:
void mainMenu();
void getPoint2DRecordsFromFile();
};
#endif
主文件
#include <iostream>
#include "main.h"
#include "Points.h"
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <stdio.h>
#include <algorithm>
class main outputMethod;
void main::getRecordsFromFile() {
std::ifstream readFile;
//put your text file name inside the ""
readFile.open("points.txt");
if (!readFile.is_open()) {
std::cout <<" "<< std::endl;
std::cout << "File Not Found!" << std::endl;
std::cout <<" "<< std::endl;
}
else {
while (readFile.good()) {
while(getline(readFile,line)) {
std::stringstream iss(line);
getline(iss, type,',');
if(type == "Points") {
getline(iss, pointX,'[');
getline(iss, pointX,',');
getline(iss, pointY ,' ');
getline(iss, pointY,']');
Points pointsConsturctor(std::stoi(pointX),std::stoi(pointY));
pointsVector.push_back(pointsConsturctor);
}
}
}
}
readFile.close();
/*error!
Non static members sortOrder found in multiple base-class subobjects of type Points*/
sort(pointsVector.begin(), pointsVector.end(),sortOrder());
for (int i = 0; i<pointsVector.size(); i++) {
std::cout << pointsVector[i].getX() << "," << pointsVector[i].getY() << std::endl;
}
}
void main::mainMenu() {
std::cout << "1. Read data " << std::endl;
std::cout << "2. sort " << std::endl;
std::cin >> input;
switch ( input ) {
case 1:
std::cout << "In Progress!" << std::endl;
break;
case 2:
getRecordsFromFile();
break;
default:
break;
std::cin.get();
}
}
int main() {
outputMethod.mainMenu();
}