我想在C++中使用get/set方法來獲取矢量。當我嘗試在我的主代碼中搜索ego_points.at(1)的索引值時,我一直收到一個拋出std :: out_of_range實例的錯誤。我下面提供我的頭文件和我的主要代碼,但我會試着在這裏解釋:在get/set方法中返回一個矢量
我有一類叫做點一個名爲ScanCallback是構建矢量scannedData,並使用公共職能設置函數設置私有向量傳輸數據等於scannedData。我主要的代碼,我有一個對象稱爲P1的點類,我想設置一個矢量稱爲ego_points等於物體的transmittedDataP1。我可以通過使用getVector()函數構建矢量ego_points,但無法訪問它的數據。任何人知道爲什麼不?
頭文件:
#pragma once
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "iostream"
#include "string"
#include "motor_driver/Motor_speeds.h"
#include "motor_driver/cartesian.h"
#include <vector>
#ifndef MOTOR_DRIVER_H
#define MOTOR_DRIVER_H
using namespace std;
using namespace motor_driver;
class Points {
public:
vector<float> scannedData;
int i;
int size;
int size1;
int size2;
Points() : scannedData(0) {} //Must match the class name. This is the constructor.
void set(vector<float> transmittingData){
transmittedData = transmittingData;
}
void ScanCallback(const sensor_msgs::LaserScan::ConstPtr& scan) {
scannedData.clear();
size = scan->ranges.size();
scannedData.resize(size);
for(i = 0; i < size; i = i + 1){
scannedData.at(i) = scan->ranges[i];
}
set(scannedData);
}
int getSize(){
return size;
}
vector<float> getVector(){
return transmittedData;
}
private:
vector<float> transmittedData;
};
#endif
主要代碼:
#include "ros/ros.h"
#include "sensor_msgs/LaserScan.h"
#include "iostream"
#include "string"
#include "motor_driver/Motor_speeds.h"
#include "motor_driver/cartesian.h"
#include <motor_driver.h>
#include <vector>
using namespace std;
using namespace motor_driver;
Points p1;
int main(int argc, char** argv) {
ros::init(argc, argv, "motor_driver_node");
ros::NodeHandle nh;
ros::Subscriber sub;
ros::Rate r(1);
int ss;
int newsize;
int index;
vector<float> ego_points;
while (ros::ok()) {
sub = nh.subscribe<sensor_msgs::LaserScan>("/scan",10, &Points::ScanCallback, &p1);
newsize = p1.getSize();
ego_points.clear();
ego_points.resize(newsize);
ego_points = p1.getVector();
cout << ego_points.at(1) << endl;
r.sleep();
ros::spinOnce();
}
return 0;
}
我的錯誤:
:~/Desktop/Naes_Thesis$ rosrun motor_driver motor_driver_node
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check
Aborted (core dumped)
你的調試器告訴你關於'p1'中包含的向量的大小是什麼? – 1201ProgramAlarm