我想要一個回傳 2 個整數向量的函式。輸入是一個字串。
插入的字串的布局應始終如下所示:“COORDINATES 123 456”,坐標為任意長度的整數。
如果字串是“COORDINATES 123”或“COORDINATES 123 456 789”,則該函式應回傳一個空向量。
#include <iostream>
#include <string>
#include <vector>
std::vector<int> getCoordinates(std::string string){
auto count = 0;
std::string coordinates;
int coordinatesInt;
std::vector<int> vector;
int i, j = 0;
for(int i = 0; i < string.size(); i ){
if(string.at(i) == ' '){
count ;
j = 1;
while(string.at(i j) != ' ' && string.at(i j) <= string.length()){
coordinates.push_back(string.at(i j));
j ;
}
coordinatesInt = std::stoi(coordinates);
vector.push_back(coordinatesInt);
}
}
if(count != 2){
vector.clear();
}
std::cout << count << std::endl;
return vector;
}
int main()
{
std::string coordinates = "COORDINATES 123 456";
std::vector<int> vectorWithCoordinates = getCoordinates(coordinates);
std::cout << vectorWithCoordinates[1] << std::endl;
//vectorWithCoordinates should now contain {123, 456}
return 0;
}
但是,當我運行此代碼時,我收到一條錯誤訊息:
terminate called after throwing an instance of "std::invalid argument"
uj5u.com熱心網友回復:
#include <iostream>
#include <string>
#include <vector>
std::vector<int> getCoordinates(std::string string){
auto count = 0;
std::string coordinates;
int coordinatesInt;
std::vector<int> vector;
for(unsigned i = 0; i < string.size(); i ){
if(string.at(i) == ' '){
count ;
unsigned j = 1;
while(i j<string.size() && string.at(i j) != ' '){ //checks that you do not go out of range before checking the content of the string
coordinates.push_back(string.at(i j));
j ;
}
coordinatesInt = std::stoi(coordinates);
vector.push_back(coordinatesInt);
}
coordinates.clear();//clears the string in order to have two different integers
}
if(count != 2){
vector.clear();
}
std::cout << count << std::endl;
return vector;
}
int main()
{
std::string coordinates = "COORDINATES 123 456";
std::vector<int> vectorWithCoordinates = getCoordinates(coordinates);
for(auto i : vectorWithCoordinates)
std::cout<<i<<"\n";
//vectorWithCoordinates should now contain {123, 456}
return 0;
}
代碼中的問題是您嘗試訪問位置 i j 處的字串內容,但不確定該位置是否超出范圍。我對您的代碼進行了最少的修改以獲得正確的輸出(我認為)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/387605.html
上一篇:括號驗證python語法問題
下一篇:Java中的回圈佇列實作
