简体   繁体   English

如何将字符串的索引保存在向量中?

[英]How to save the index of a string in a vector?

Let's say I have a function int pozvec(vector<string> vect) which takes as parameter a pre-filled vector of strings.假设我有一个 function int pozvec(vector<string> vect) ,它将一个预填充的字符串向量作为参数。

I want to know at which position i there is the character "p", specifically "p" .我想知道在哪个 position i有字符“p”,特别是“p” All of the strings are single-character, but the vector is declared as containing strings.所有字符串都是单字符,但向量被声明为包含字符串。 I want to save the index at which "p" is found in a variable x;我想保存在变量 x 中找到“p”的索引;

for(int i=0; i<vect.size(); i++)
    if(vect[i] == "p")
        x=i;

does not seem to work.似乎不起作用。 Nor does strcmp , at all. strcmp 也没有 The problem is more complex, but the part that doesn't work is this one.问题更复杂,但不起作用的部分是这个。

Thank you in advance for your help!预先感谢您的帮助!

By that function, your storing the index of the last occurrence of the string your looking for.通过该 function,您存储了您要查找的字符串的最后一次出现的索引。 This is because your not exiting from the loop once the first occurrence was found.这是因为一旦找到第一次出现,您就不会退出循环。

To exit from a loop conditionally, use the break statement.要有条件地退出循环,请使用break语句。

for(int i = 0; i< vect.size(); i++)
{
    if(vect[i] == "p")
    {
        x=i;
        break;
    }
}

Now it will exit right after the first occurrence was found.现在它将在找到第一个事件后立即退出。

You also have another option in the form of std::find .您还可以选择std::find形式的另一种选择。

int index = std::find(vect.begin(), vect.end(), "P") - vect.begin()

I don't know what you really want to do, but this worked perfectly fine for me:我不知道你真正想做什么,但这对我来说非常好:

for (size_t i {}; i < vec.size(); ++i) {
   if (vec.at(i) == "p") {
       x = i;
       break; // I don't know wether you want to break here or not
   } else {
       continue;
   }
}

Or if you all strings include just one character this should also work:或者,如果你所有的字符串都只包含一个字符,这也应该有效:

for (size_t i {}; i < vec.size(); ++i) {
   if (vec.at(i).at(0) == 'p') {
       x = i;
       break; // I don't know wether you want to break here or not
   } else {
       continue;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM