有没有办法打印出数组成员的索引?

时间:2019-03-05 17:13:25

标签: c++ arrays

例如,我有一个读取的数组:

.AAAA {
box-shadow:none;
border:none;
background-color:transparent;
}
.leaflet-tooltip-top:before,
.leaflet-tooltip-bottom:before,
.leaflet-tooltip-left:before,
.leaflet-tooltip-right:before {
    border: none !important;
}

如果我这样做:

std::string month[] = {January, February, March, April, May, June, July, 
August, September, October, November, December};

它打印出“ March”,但是如果我希望它打印出它位于数组内部的时间顺序值怎么办?即“ 2”。

2 个答案:

答案 0 :(得分:1)

您可以std::find数组中的字符串,然后从数组的开头计算其中的std::distance

std::string month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

std::size_t getIndex(const std::string & text) {
    auto pos = std::find(std::begin(month), std::end(month), text);
    return std::distance(std::begin(month), pos);
}

int main() {
    std::cout << getIndex("March") << " " << getIndex("Not a month");
}

带有输出

2 12

答案 1 :(得分:0)

似乎您要打印位于索引2处的数组元素的索引。您可以这样做:

std::cout << 2;