【发布时间】:2022-01-19 21:24:55
【问题描述】:
我想要一个返回 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"
【问题讨论】:
-
terminate 在抛出“std::out_of_range”实例后调用——这意味着其中一个
at()调用告诉你你要出去了——界外。下一项工作是让您调试代码并确定它是哪个at调用。 -
顺便说一句,代码不必如此复杂即可完成您正在寻找的任务。如果您使用
std::istringstream,则根本不需要检查空格。这也消除了对at()调用的需要。 -
string.at(i+j)当i是字符串中的最后一个字符时,i+j将离开字符串的末尾,因为j从 1 开始。 -
@RichardCritten 我已经改变了这个,但现在我得到一个无效的论点。我已经更改了问题和开场白。
-
@helloWorld See this。比尝试越界索引要简单得多。
标签: c++ algorithm vector compiler-errors stoi