find() 没有返回可以使用的 int 值,并且在编译之前给出错误

find() is not returning an int value that can be used and is giving an error before compiling

本文关键字:编译 错误 出错 返回 可以使 int find      更新时间:2023-10-16

>我正在尝试获取创建的新向量的索引值,但是find((函数不允许我为变量分配所述find((的返回值

我尝试在其他地方分配值,摆弄起点和终点,但程序根本不会用 find(( 的值分配 tempind。

void count_city(vector<string> city, vector<string> state) {
vector<string> cities(4);
vector<int> counted(4);
string temp = " ";
int tempind = 0;
for (int i = 0; i < city.size(); i++) {
temp = city.at(i);
if (find(cities.begin(), cities.end(), temp) != cities.end()) {
continue;
}
else {
cities.push_back(temp);
}
tempind = (find(cities.begin(), cities.end(), temp));
counted.at(tempind) = count(city.begin(), city.end(), temp);
}
}

我只是希望 tempind 成为矢量城市中城市的索引,但它不允许我编译并给我一个错误,指出我的类型不同。

std::find()返回迭代器,而不是索引。 如果需要索引,可以将迭代器传递给std::distance()

auto found = find(cities.begin(), cities.end(), temp);
tempind = distance(cities.begin(), found);

但在这种情况下,您根本不需要find()索引。由于push_back()插入向量的末尾,因此所需的索引是push_back()向量之前的大小:

for (int i = 0; i < city.size(); i++) {
temp = city[i];
if (find(cities.begin(), cities.end(), temp) != cities.end()) {
continue;
}
tempind = cities.size();
cities.push_back(temp);
counted.at(tempind) = count(city.begin(), city.end(), temp);
}