在数组C ++中搜索字符串索引

时间:2013-10-21 17:34:49

标签: c++

我试图找到数组中元素的索引....我设法使用以下函数使用int:

int *getIndexOfInt(int *arr, int size, int check) {
  int *result;
  int *k;
  int count = 0;
  for (int i = 0; i <= size - 1; i++) {
    if (arr[i] == check) {
      k[count] = i;
      count++;
    }

  }
  if (count > 0) {
    *result = *k;
    return result;
  } else
    cout << "Not Found";
}

然而,当我尝试使用字符串时,它只是给了我错误(程序退出状态为11)或无限循环:

int *getIndexOfString(string *arr, int size, string check) {
    int *result;
    int *k;
    int count = 0;
    for (int i = 0; i <= size - 1; i++) {

         if (arr[i] == check) {

            k[count] = i;
            count++;
          }

    }

    if (count > 0) {

        *result = *k;
        return result;
  } 
   else cout << "Not Found";
}

你能告诉我为什么,也许可以帮我解决错误吗?

修改 的 结果变量是在main函数中使用的数组,它包含在给定数组中找到字符串的索引。 k变量只是一个数组,其中值被添加到结果中之前存储。 arr是给定的字符串数组,大小是givven大小,check是代码搜索的字符串。

4 个答案:

答案 0 :(得分:3)

首先,您正在访问未初始化的内存。奇怪的是,你的第一个代码是有效的。但是,它可能是特定于编译器的(这些事情在C ++中发生了很多)。

局部变量通常在堆栈上分配,C ++不保证任何默认值。因此,一种可能的解释是(在相同的内存地址,保存指针的位置)另一个有效的指针。现在,当您创建此局部变量时,它只是获得了这个“旧”地址,因此它可以访问一些以前分配的内存。只是暂时不关心它,即使它有效,相信我们 - 你不应该依赖于此。 : - )

另一个问题是返回的值。当你不知道那个数组的大小时,你如何使用它?您应该返回类似std :: vector&lt;&gt;,某些结构或类似内容的内容。不只是指向未知长度的数组!

结果:您的代码太复杂了。看到更好的解决方案:

#include <iostream>
#include <string>
#include <vector>

std::vector<int> getIndexes(std::vector<std::string> &input, std::string searched) {
    std::vector<int> result;

    for (int i = 0; i < input.size(); i++) {
        if (input[i] == searched) {
            result.push_back(i);
        }
    }

    return result;
}

int main(int argc, char *argv[]) {
    std::vector<std::string> greetings;
    greetings.push_back("hello");
    greetings.push_back("hi");
    greetings.push_back("bye");
    greetings.push_back("hi");
    greetings.push_back("hello");
    greetings.push_back("bye");

    std::vector<int> indexes = getIndexes(greetings, "hi");

    for (int i = 0; i < indexes.size(); i++) {
        std::cout << indexes[i] << std::endl;
    }

    return 0;
}

答案 1 :(得分:1)

您的主要问题是您没有将结果指针初始化为有效数组。实际上你应该返回一个索引向量而不是一个指针,这样调用者就知道了这个大小,而不必手动管理内存。像这样:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

vector<int> getIndicesOfString(const vector<string>& in, const string& check) {
    vector<int> ret;
    for (auto it = cbegin(in); it != cend(in); ++it) {
        if (*it == check) ret.push_back(distance(cbegin(in), it));
    }
    return ret;
}

int main() {
    auto v = vector<string>{"red", "orange", "yellow", "green", "blue", "indigo", "violet", "red"};
    auto indices = getIndicesOfString(v, "red");
    copy(cbegin(indices), cend(indices), ostream_iterator<int>(cout, ", "));
}

答案 2 :(得分:0)

使用矢量编辑:

std::vector<int> getIndexOfString(string *arr, int size, string check)
{
  std::vector<int> iVect;
  for (int i = 0; i <= size - 1; i++)
  {
    if (arr[i] == check)
    {
      iVect.push_back (i);
      cout << "Found at " << i << endl;
    }
  }

  if (iVect.empty)
     cout << "not found" << endl;

  return iVect;
}

您的函数有太多未初始化的指针。你真的想要返回索引或指针吗?您还缺少失败案例的返回值。

答案 3 :(得分:0)

其他人已提出建议,在此我将其作为参考。

您可以使用标准库。特别是算法std::find

#include<vector>
#include<string>
#include<iostream>
#include<algorithm>

int main() {
  std::vector<std::string> words = {"one", "two", "three", "four", "five"};
  size_t index = std::distance(words.begin(),
                               std::find(words.begin(), words.end(), "three"));
  std::cout<<"Index: "<<index<<std::endl;
}

编译为(GCC 4.8.1 OS X 10.7.4):

g++ indices-in-array.cpp -std=c++11

输出:

Index: 2
相关问题