Exemplo n.º 1
0
vector<int> searchRange(int A[], int n, int target) {
    auto lower = lower_bound(A, A+n, target);
    auto upper = upper_bound(A, A+n, target);
    if (lower == A + n || *lower != target)
        return vector<int> {-1, -1};
    return vector<int> {distance(A, lower), distance(A, prev(upper))};
}
Exemplo n.º 2
0
            auto operator()(const C & c1, const C & c2) const {
                using std::distance;
                using std::copy;

                auto c1_size = distance(c1.begin(), c1.end());
                auto c2_size = distance(c2.begin(), c2.end());
                C r(c1_size + c2_size);

                auto end = copy(c1.begin(), c1.end(), r.begin());
                copy(c2.begin(), c2.end(), end);

                return r;
            }
void MyHeap<Key, Element>::insertItem(const Key& k, const Element& e) {
    heap.push_back(item(k, e));
        
    iterator parent = heap.end() - distance(heap.begin()++, heap.end()) / 2;
    if (parent > heap.end()) {
        parent = heap.begin();
    }
    iterator child = heap.end();
    
    
    while (child->first < parent->first) {
        swap(*child, *parent);
        child = parent;
        parent = child - distance(heap.begin()++, child) / 2;
    }
}
// Checks whether a filter is empty and checks invariants.
static void expect_empty(const filter_t &c) {
  EXPECT_TRUE(c.empty());
  EXPECT_EQ(0, c.size());
  EXPECT_EQ(0, distance(c.begin(), c.end()));
  EXPECT_FLOAT_EQ(0.0f, c.load_factor());
  EXPECT_LE(c.load_factor(), c.max_load_factor());
}
Exemplo n.º 5
0
int main (int argc, char* argv[])
{
    ifstream input_file(argv[1]);
    string line;

    if (input_file)
    {
        while (getline(input_file, line))
        {
            vector<string> entries = tokenize(line);
            vector<int> dots;
            for (int i = 0; i < entries.size(); ++i)
            {
                string entry = entries[i];
                // special case for failure on CodeEval's end
                if (entry == "XYYYY.Y")
                    entry = "XYYYYYY";
                dots.push_back(count(entry.begin(), entry.end(), '.'));
            }
            cout << dots[distance(dots.begin(), min_element(dots.begin(), dots.end()))] << endl;
        }
        input_file.close();
    }
    return 0;
}
Exemplo n.º 6
0
QModelIndex directory_model::find(std::string const & file_name) const
{
    list<file_info>::const_iterator it = find_if(_files.begin(), _files.end(), find_by_name{file_name});
    if (it != _files.end())
        return index(distance(_files.begin(), it));
    else
        return QModelIndex{};
}
Exemplo n.º 7
0
static inline uint8_t closest_index(const vector<float>& values, float key) {
    vector<float> differences;
    differences.resize(values.size());

    transform(values.begin(), values.end(), differences.begin(), [key](const float val) {
        return fabs(val - key);
    });
    return distance(differences.begin(), min_element(differences.begin(), differences.end()));
}
size_t
reserve_count_for_single_pass_helper(InputIterator first, InputIterator last,
                                     std::random_access_iterator_tag)
{
    using std::distance;
    typename std::iterator_traits<InputIterator>::difference_type n =
        distance(first, last);
    return (size_t)n;
}
Exemplo n.º 9
0
MultiModLocGen::MultiModLocGen(MultiModLocGen const &rhs) :
    _super(rhs) {
    using std::distance;
    _rangeMap = rhs._rangeMap;

    range_map_type::difference_type dist = 
        distance(_rangeMap.begin(), rhs._rangeIt);
    _rangeIt = std::next(_rangeMap.begin(), dist);

}
Exemplo n.º 10
0
ForwardIterator upper_bound(ForwardIterator first, ForwardIterator last, T value) {
    while (first != last) {
        auto mid = next(first, distance(first, last) / 2);
        if (value >= *mid)
            first = ++mid;
        else
            last = mid;
    }
    return first;
}
Exemplo n.º 11
0
void
wait_all(ForwardIterator first, ForwardIterator last)
{
  typedef typename std::iterator_traits<ForwardIterator>::difference_type
    difference_type;

  using std::distance;

  difference_type num_outstanding_requests = distance(first, last);

  std::vector<bool> completed(num_outstanding_requests);

  while (num_outstanding_requests > 0) {
    bool all_trivial_requests = true;

    difference_type idx = 0;
    for (ForwardIterator current = first; current != last; ++current, ++idx) {
      if (!completed[idx]) {
        if (optional<status> stat = current->test()) {
          // This outstanding request has been completed.
          completed[idx] = true;
          --num_outstanding_requests;
          all_trivial_requests = false;
        } else {
          // Check if this request (and all others before it) are "trivial"
          // requests, e.g., they can be represented with a single
          // MPI_Request.
          all_trivial_requests =
            all_trivial_requests
            && !current->m_handler
            && current->m_requests[1] == MPI_REQUEST_NULL;
        }
      }
    }

    // If we have yet to fulfill any requests and all of the requests
    // are trivial (i.e., require only a single MPI_Request to be
    // fulfilled), call MPI_Waitall directly.
    if (all_trivial_requests
        && num_outstanding_requests == (difference_type)completed.size()) {
      std::vector<MPI_Request> requests;
      requests.reserve(num_outstanding_requests);
      for (ForwardIterator current = first; current != last; ++current)
        requests.push_back(current->m_requests[0]);

      // Let MPI wait until all of these operations completes.
      BOOST_MPI_CHECK_RESULT(MPI_Waitall,
                             (num_outstanding_requests, &requests[0],
                              MPI_STATUSES_IGNORE));

      // Signal completion
      num_outstanding_requests = 0;
    }
  }
}
Exemplo n.º 12
0
bool SelectLongOperation::selectOption(const std::string& str) {
  std::vector<Option>::iterator it =
      find_if(options_.begin(), options_.end(), bind(&Option::str, _1) == str);

  if (it != options_.end() && it->shown) {
    selected(distance(options_.begin(), it));
    return true;
  }

  return false;
}
Exemplo n.º 13
0
MultiModLocGen& MultiModLocGen::operator=(MultiModLocGen const &rhs) {
    if (this != &rhs) {
        using std::distance;
        _super::operator=(static_cast<_super const&>(rhs));
        _rangeMap = rhs._rangeMap;
        range_map_type::difference_type dist =
            distance(_rangeMap.begin(), rhs._rangeIt);
        _rangeIt = std::next(_rangeMap.begin(), dist);
    }
    return *this;
}
Exemplo n.º 14
0
void replace(string &s, const string &oldVal, const string &newVal)
{
	for (auto iter = s.begin(); distance(iter, s.end()) >=
		static_cast<ptrdiff_t>(oldVal.size()); ++iter)
	{
		if (*iter == oldVal[0] && string(iter, std::next(iter, oldVal.size()))
			== oldVal)
		{
			iter = s.erase(iter, std::next(iter, oldVal.size()));
			iter = s.insert(iter, newVal.cbegin(), newVal.cend());
		}
	}
}
Exemplo n.º 15
0
char VersificationMgr::System::getVerseFromOffset(long offset, int *book, int *chapter, int *verse) const {

	if (offset < 1) {	// just handle the module heading corner case up front (and error case)
		(*book) = -1;
		(*chapter) = 0;
		(*verse) = 0;
		return offset;	// < 0 = error
	}

	// binary search for book
	vector<Book>::iterator b = lower_bound(p->books.begin(), p->books.end(), offset, BookOffsetLess());
	if (b == p->books.end()) b--;
	(*book)    = distance(p->books.begin(), b)+1;
	if (offset < (*(b->p->offsetPrecomputed.begin()))-((((!(*book)) || (*book)==BMAX[0]+1))?2:1)) { // -1 for chapter headings
		(*book)--;
		if (b != p->books.begin()) {
			b--;	
		}
	}
	vector<long>::iterator c = lower_bound(b->p->offsetPrecomputed.begin(), b->p->offsetPrecomputed.end(), offset);

	// if we're a book heading, we are lessthan chapter precomputes, but greater book.  This catches corner case.
	if (c == b->p->offsetPrecomputed.end()) {
		c--;
	}
	if ((offset < *c) && (c == b->p->offsetPrecomputed.begin())) {
		(*chapter) = (offset - *c)+1;	// should be 0 or -1 (for testament heading)
		(*verse) = 0;
	}
	else {
		if (offset < *c) c--;
		(*chapter) = distance(b->p->offsetPrecomputed.begin(), c)+1;
		(*verse)   = (offset - *c);
	}
	return ((*chapter > 0) && (*verse > b->getVerseMax(*chapter))) ? KEYERR_OUTOFBOUNDS : 0;
}
Exemplo n.º 16
0
void directory_model::make_directory(QString local_name)
{
    string dirname = local_name.toStdString();

    _sys->mkdir(_path / dirname);  // TODO: ak sa mkdir nepodari, nevkladaj

    file_info item{dirname, true};
    auto insert_it = lower_bound(_files.begin(), _files.end(), item, file_compare);
    int row = distance(_files.begin(), insert_it);

    beginInsertRows(QModelIndex{}, row, row);
    _files.insert(insert_it, item);
    endInsertRows();

    emit current_index_changed(index(row));
}
static void expect_contents(const quotient_filter<T, H, B> &c,
                            const initializer_list<size_t> hash_list) {
  ASSERT_TRUE(hash_list.size() > 0) << "For empty filters use expect_empty()";

  EXPECT_FALSE(c.empty());
  EXPECT_EQ(hash_list.size(), c.size());
  EXPECT_EQ(ptrdiff_t(hash_list.size()), distance(c.begin(), c.end()));
  EXPECT_FLOAT_EQ(float(c.size()) / c.slot_count(), c.load_factor());
  EXPECT_LE(c.load_factor(), c.max_load_factor());

  auto it = c.begin();
  for (const size_t hash : hash_list) {
    ASSERT_TRUE(it != c.end());
    EXPECT_EQ(hash, *it++);
  }
  EXPECT_TRUE(it == c.end());
}
Exemplo n.º 18
0
    Group(const StdRange& range)
    {
        using std::begin;
        using std::end;
        using std::distance;

        auto b = begin(range);
        auto e = end(range);

        _names.reserve(distance(b, e));

        auto i = b;
        while(i != e)
        {
            _names.push_back(GetName(*i));
            ++i;
        }
    }
Exemplo n.º 19
0
void merge_sort_x(vector<point_seg_pair>::iterator first, vector<point_seg_pair>::iterator last)
{

	size_t size = distance(first, last);

	//base case
	if (size <=1)
		return;

	//recursive case
	auto middle = first;
	advance(middle, size/2);

	merge_sort_x(first, middle);
	merge_sort_x(middle, last);

	stable_merge_x(first, middle, last);
}
Exemplo n.º 20
0
void stable_merge_y(vector<point_seg_pair>::iterator first, vector<point_seg_pair>::iterator middle, vector<point_seg_pair>::iterator last)
{
	vector<point_seg_pair> buffer(distance(first, last));

	auto in1 = first;
	auto in2 = middle;
	auto out = buffer.begin();

	while(in1 != middle && in2 != last)
	{
		if(in2->first.y < in1->first.y)
			*out++ = *in2++;
		else
			*out++ = *in1++;
	}

	copy(in1, middle, out);
	copy(in2, last, out);
	copy(buffer.begin(), buffer.end(), first);
}
map<long, int> getCheckMap(const map<long, vector<double> >& ratingMatrix, map<int, vector<double> >& clusterCenters)
{
	map<long, int> checkMap;

	for(map<long, vector<double> >::const_iterator rating_iter = ratingMatrix.begin(); rating_iter != ratingMatrix.end(); rating_iter++)
	{
	    // Use only if want to see al the distaces
	    //This will hold the Canberra distances for the current user
	    vector<double> distance(clusterCenters.size());

	    //cout<<"Calculating Cluster Assignment for user: "******" ";

			// Calculate the canberra distance
			currentDistance = exp(-cosineSimilarity(vector<double>(rating_iter->second.begin(), rating_iter->second.end()), vector<double>(cluster_it->second.begin(), cluster_it->second.end())));
				
			// TODO:: TODO:: check for multiple matches to minvalue
			if(currentDistance < minValue)
			{
			    minValue = currentDistance;
			    minIndex = cluster_it->first;
			}

	    }

	    // Set the cluster for the corresponding user
	    checkMap[rating_iter->first] = minIndex;		
	}

	return checkMap;
}
void Shmem::SendVector(
    const Vector::const_iterator& first,
    const Vector::const_iterator& last,
    const int dest_pe)
{
    #ifdef DEBUG
    cout << INDENT(4) << "Shmem::SendVector()..." << endl;
    #endif
    for (auto it = first; it != last; it++)
    {
        const Index index = distance(first, it);
        IndexElemPair p(index, *it);
        #ifdef DEBUG
        cout << INDENT(5) << "Index = " << p.first
            << ", Value = " << p.second << endl;
        #endif
        shmem_send(&p, HandlerNumber(), sizeof(p), dest_pe);
        Stats::SendOpCounterInc();
        Stats::SendDataCounterAdd(sizeof(p));
    }
    #ifdef DEBUG
        cout << INDENT(4) << "Shmem::SendVector() return" << endl;
    #endif
}
Exemplo n.º 23
0
json JSONFormatter::compose_object( const Resource& value ) const
{
    auto object = json::object( );
    
    for ( auto iterator = value.begin( ); iterator not_eq value.end( ); iterator++ )
    {
        auto iterators = value.equal_range( iterator->first );
        const auto length = distance( iterators.first, iterators.second );
        
        if ( length > 1 )
        {
            auto items = json::array( );
            
            for ( auto item = iterators.first; item not_eq iterators.second; item++ )
            {
                auto field = String::to_string( item->second );
                
                if ( String::is_boolean( field ) )
                {
                    items.push_back( String::lowercase( field ) == "true" );
                }
                else if ( String::is_integer( field ) )
                {
                    try
                    {
                        items.push_back( stol( field ) );
                    }
                    catch ( const out_of_range& )
                    {
                        items.push_back( field );
                    }
                }
                else if ( String::is_fraction( field ) )
                {
                    try
                    {
                        items.push_back( stod( field ) );
                    }
                    catch ( const out_of_range& )
                    {
                        items.push_back( field );
                    }
                }
                else
                {
                    items.push_back( field );
                }
            }
            
            object[ iterator->first ] = items;
            
            advance( iterator, length - 1 );
        }
        else
        {
            auto field = String::to_string( iterator->second );
            
            if ( String::is_boolean( field ) )
            {
                object[ iterator->first ] = ( String::lowercase( field ) == "true" );
            }
            else if ( String::is_integer( field ) )
            {
                try
                {
                    object[ iterator->first ] = stol( field );
                }
                catch ( const out_of_range& )
                {
                    object[ iterator->first ] = field;
                }
            }
            else if ( String::is_fraction( field ) )
            {
                try
                {
                    object[ iterator->first ] = stod( field );
                }
                catch ( const out_of_range& )
                {
                    object[ iterator->first ] = field;
                }
            }
            else
            {
                object[ iterator->first ] = field;
            }
        }
    }
    
    return object;
}
Exemplo n.º 24
0
size_t DataStream::getPosition()const
{
    return distance(this->beg, this->iter);
}
Exemplo n.º 25
0
 Index findTranscriptID( const std::string &tname ) {
     using std::distance;
     using std::lower_bound;
     auto it = lower_bound( _transcriptNames.begin(), _transcriptNames.end(), tname );
     return ( it == _transcriptNames.end() ) ? INVALID : ( distance(_transcriptNames.begin(), it) );
 }
Exemplo n.º 26
0
size_t ArgMax(const VectorL<T>& v)
{
    return v.beginRow_ +
           distance(v.storage_.begin(), max_element(v.storage_.begin(), v.storage_.end()));
}
Exemplo n.º 27
0
OutputIterator
wait_all(ForwardIterator first, ForwardIterator last, OutputIterator out)
{
  typedef typename std::iterator_traits<ForwardIterator>::difference_type
    difference_type;

  using std::distance;

  difference_type num_outstanding_requests = distance(first, last);

  std::vector<status> results(num_outstanding_requests);
  std::vector<bool> completed(num_outstanding_requests);

  while (num_outstanding_requests > 0) {
    bool all_trivial_requests = true;
    difference_type idx = 0;
    for (ForwardIterator current = first; current != last; ++current, ++idx) {
      if (!completed[idx]) {
        if (optional<status> stat = current->test()) {
          // This outstanding request has been completed. We're done.
          results[idx] = *stat;
          completed[idx] = true;
          --num_outstanding_requests;
          all_trivial_requests = false;
        } else {
          // Check if this request (and all others before it) are "trivial"
          // requests, e.g., they can be represented with a single
          // MPI_Request.
          all_trivial_requests =
            all_trivial_requests
            && !current->m_handler
            && current->m_requests[1] == MPI_REQUEST_NULL;
        }
      }
    }

    // If we have yet to fulfill any requests and all of the requests
    // are trivial (i.e., require only a single MPI_Request to be
    // fulfilled), call MPI_Waitall directly.
    if (all_trivial_requests
        && num_outstanding_requests == (difference_type)results.size()) {
      std::vector<MPI_Request> requests;
      requests.reserve(num_outstanding_requests);
      for (ForwardIterator current = first; current != last; ++current)
        requests.push_back(current->m_requests[0]);

      // Let MPI wait until all of these operations completes.
      std::vector<MPI_Status> stats(num_outstanding_requests);
      BOOST_MPI_CHECK_RESULT(MPI_Waitall,
                             (num_outstanding_requests, &requests[0],
                              &stats[0]));

      for (std::vector<MPI_Status>::iterator i = stats.begin();
           i != stats.end(); ++i, ++out) {
        status stat;
        stat.m_status = *i;
        *out = stat;
      }

      return out;
    }

    all_trivial_requests = false;
  }

  return std::copy(results.begin(), results.end(), out);
}
Exemplo n.º 28
0
Arquivo: main.cpp Projeto: CCJY/coliru
 void static do_annotate(ast::LocationInfo& li, It f, It l, It first) {
     using std::distance;
     li.line   = get_line(f);
     li.column = get_column(first, f);
     li.length = distance(f, l);
 }
Exemplo n.º 29
0
            auto operator()(const C & c) const {
                using std::distance;

                return distance(c.begin(), c.end());
            }