When I tried to use this function to remove items in the vector that are NaN
in the following, unsorted
is a vector filled with items of strings, and sanitised
is an empty double
vector
...
1 void sensitising(vector <string> unsorted)
2 {
3 double x = 0;
4 for (int i = 0; i < sizeof(unsorted); i++)
5 {
6 x = stod(unsorted[i]);
7 if (isnan(x)==false)
8 {
9 sanitised.push_back(x);
10 }
11 }
12}
...
an error was thrown at line 6 complaining vector subscript out of range
if line 9 is replaced with cout << "is a number";
then the error will be thrown after all the items are correctly printed as
is a number
is a number
is a number
...
any idea why? Thanks!
sizeof
does not tell you the length of the vector. It tells you the size (in bytes) of the actual object.
To get the number of items stored in the vector, use unsorted.size()
.
Note that in C++11 and later, you can iterate your vector more easily with a range-based loop:
for (const auto& str : unsorted) {
double x = stod(str);
if (!isnan(x)) {
sanitised.push_back(x);
}
}
如果要获取向量的大小(项的数量),则应使用vector.size()
而不是sizeof(vector)
,它返回以char为单位的内存中的向量大小(C ++标准)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.