简体   繁体   English

如何使用STL将数组转换为向量

[英]How to convert arrays to vectors using STL

This code is a linear search program using arrays. 此代码是使用数组的线性搜索程序。 Out of curiosity, I was wondering how this code could be rewritten using STL vectors in place of arrays but still have the same output. 出于好奇,我想知道如何使用STL向量代替数组来重写此代码,但仍然具有相同的输出。

#include <iostream>
#include <string>
using namespace std;

template <typename T>
int linearSearch(T list[], int key, int arraySize)
{
  for (int i = 0; i < arraySize; i++)
  {
    if (key == list[i])
      return i;
  }

  return -1;
}

int main()
{
  int intArray[] =
  {
    1, 2, 3, 4, 8, 15, 23, 31
  };
  cout << "linearSearch(intArray, 3, 8) is " << linearSearch(intArray, 3, 8) << endl;
  cout << "linearSearch(intArray, 10, 8) is " << linearSearch(intArray, 10, 8) << endl;

  return 0;
}
template <typename T>
int linearSearch(const vector<T> &list, const T &key)
{
    auto itr = std::find(list.begin(), list.end(), key);

    if (itr != list.end())
        return std::distance(list.begin(), itr);
    else
        return -1;
}

int main()
{
    int intArray[] = {1, 2, 3, 4, 8, 15, 23, 31};

    std::vector<int> vec(intArray, intArray + 8);

    int i = linearSearch(vec, 15);
}

Note: C++11 is enabled 注意:已启用C ++ 11

you can do it by changing your parameter type and in main. 您可以通过更改参数类型和main来实现。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <typename T>
int linearSearch(vector<T> list, int key)
{
   for (size_t i = 0; i < list.size(); i++)
   {
      if (key == list[i])
        return i;
   }

   return -1;
}

int main()
{
  int intArray[] =
  {
    1, 2, 3, 4, 8, 15, 23, 31
   };
   vector<int> list(intArray, intArray+8);

   cout << "linearSearch(list, 3,) is " << linearSearch(list, 3) << endl;
   cout << "linearSearch(list, 10) is " << linearSearch(list, 10) << endl;

   return 0;
}

With as few changes as possible you could do this: 使用尽可能少的更改,您可以执行以下操作:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

// Using const std::vector<T> & to prevent making a copy of the container
template <typename T>
int linearSearch(const std::vector<T> &list, int key)
{
  for (size_t i = 0; i < list.size(); i++)
  {
    if (key == list[i])
      return i;
  }

  return -1;
}

int main()
{
  std::vector<int> arr = { 1 ,2, 3, 4, 8, 15, 23, 31 } ;

  cout << "linearSearch(intArray, 3) is " << linearSearch(arr, 3) << endl;
  cout << "linearSearch(intArray, 10) is " << linearSearch(arr, 10) << endl;

  return 0;
}

I would recommend not using using namespace std; 我建议不要using namespace std; .

This could work (it is based on the STL implementation): 这可能有效(它基于STL实现):

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

using namespace std;

template <typename ForwardIter, typename Type>
int linearSearch(ForwardIter beg, ForwardIter end, Type key )
{
  int i = 0;
  for (;beg != end; ++beg)
  {
    if (key == *beg)
      return i;
    i++;
  }

  return -1;
}

int main()
{
  vector< int > vec = { 1, 2, 3, 4, 5, 6, 7 };
  cout << "linearSearch 1 is " << linearSearch(vec.begin(), vec.end(), 4) << endl;
  cout << "linearSearch 2 is " << linearSearch(vec.begin()+2, vec.end(), 1) << endl;

  return 0;
}

Note: it can also work for, std::list and std::deque . 注意:它也可以用于std::liststd::deque I think it will produce correct results even in a normal array. 我认为即使以普通数组也可以产生正确的结果。

 template <typename T>
 int linearSearch(T list, int key)

Changing the two first lines of your code as above, as well as replacing arraySize with list.size() should suffice for any kind of container supporting operator [] (including vectors), and indices as consecutive int . 如上更改代码的前两行,并用list.size()替换arraySize应该足以支持任何类型的支持operator []的容器(包括向量),并将索引作为连续的int

Note that while your template tries to abstract the content of the array as the typename T , it implicitely assumes it is int in the type of key . 请注意,当您的模板尝试将数组的内容抽象为类型名T ,它隐式地假定key类型为int A more generic implementation would be: 一个更通用的实现是:

template <typename T>
int linearSearch(T list, typename T::value_type key)

Another issue in this solution is the passing mode of list . 此解决方案中的另一个问题是list的传递模式。 We can overcome this issue by converting it to a reference like so: 我们可以通过将其转换为如下引用来克服此问题:

// includes ...
#include <type_traits>
using namespace std;

template <typename T>
int linearSearch(add_lvalue_reference<T> list, typename T::value_type key){
    for (size_t i = 0; i < list.size(); i++) {
        if (key == list[i])
            return i;
    }
    return -1;
}

You probably asked for the something like this (std::vector is used instead of hand-made class): 您可能会要求类似这样的东西(使用std :: vector而不是手工制作的类):

const size_t count = 8; 
int values[count] = {1, 2, 3, 4, 8, 15, 23, 31};
std::vector<int> intArray;
intArray.assign(values, values + count);

std::vector<int>::iterator val1 = std::find(intArray.begin(), intArray.end(), 3);
int pos1 = (val1 != intArray.end()) ? (val1 - intArray.begin()) : -1;

std::vector<int>::iterator val2 = std::find(intArray.begin(), intArray.end(), 10);
int pos2 = (val2 != intArray.end()) ? (val2 - intArray.begin()) : -1;

cout << "linearSearch(intArray, 3, 8) is " << pos1 << endl;
cout << "linearSearch(intArray, 10, 8) is " << pos2 << endl;

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

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